经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » Echarts » 查看文章
vue3+ts打开echarts的正确方式
来源:cnblogs  作者:唯之为之  时间:2023/12/29 9:16:55  对本文有异议

实例项目使用 vite5 + vue3 + ts,项目地址 vite-vue3-charts,预览地址 https://weizwz.com/vite-vue3-charts

准备工作

1. 注册为百度地图开发者

官网地址,然后在 应用管理 -> 我的应用 里,创建应用,创建好后复制 AK
image

2. 在根目录的 index.html 里引入百度地图

  1. <head>
  2. <meta charset="UTF-8" />
  3. <link rel="icon" type="image/svg+xml" href="/vite.svg" />
  4. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  5. <title>xxx</title>
  6. <script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=你复制好的AK"></script>
  7. </head>

head 里引入,是为了提前加载进来

3. 安装 echarts

  1. npm i echarts -S

封装

1. 增加ts对百度地图的支持

修改 .eslintrc.cjs,加入对百度地图的支持

  1. module.exports = {
  2. // 其他省略
  3. globals: {
  4. BMap: true
  5. }
  6. }

2. 全局注册 echarts

修改 main.ts

  1. // 引入 echarts
  2. import * as echarts from 'echarts'
  3. import themeJSON from '@/assets/weizwz.json'
  4. echarts.registerTheme('weizwz', themeJSON)
  5. const app = createApp(App)
  6. // 全局挂载 echarts
  7. app.config.globalProperties.$echarts = echarts

3. 封装 echarts

src/components 下新建 chart 文件夹,并在其下新建 index.vue,封装如下

  1. <script setup lang="ts">
  2. import { onMounted, getCurrentInstance, defineExpose, ref } from 'vue'
  3. defineOptions({
  4. name: 'WChart'
  5. })
  6. // defineExpose 让父组件可调用此方法
  7. defineExpose({
  8. setData
  9. })
  10. // 组件传参
  11. const props = defineProps({
  12. width: {
  13. type: String, //参数类型
  14. default: '100%', //默认值
  15. required: false //是否必须传递
  16. },
  17. height: {
  18. type: String,
  19. default: '10rem',
  20. required: true
  21. },
  22. option: {
  23. type: Object,
  24. default: () => {
  25. return {}
  26. },
  27. required: true
  28. },
  29. // 初始化之前的工作,比如加载百度地图相关数据
  30. initBefore: {
  31. type: Function,
  32. required: false
  33. },
  34. // 初始化之后的工作,比如添加百度地址控件
  35. initAfter: {
  36. type: Function,
  37. required: false
  38. }
  39. })
  40. let chart: { setOption: (arg0: Record<string, any>) => void; resize: () => void }
  41. const wchart = ref(null)
  42. //声明周期函数,自动执行初始化
  43. onMounted(() => {
  44. init()
  45. // 监控窗口大小,自动适应界面
  46. window.addEventListener('resize', resize, false)
  47. })
  48. //初始化函数
  49. function init() {
  50. // 基于准备好的dom,初始化echarts实例
  51. const dom = wchart.value
  52. // 通过 internalInstance.appContext.config.globalProperties 获取全局属性或方法
  53. let internalInstance = getCurrentInstance()
  54. let echarts = internalInstance?.appContext.config.globalProperties.$echarts
  55. chart = echarts.init(dom, 'weizwz')
  56. // 渲染图表
  57. if (props.initBefore) {
  58. props.initBefore(chart).then((data: Record<string, any>) => {
  59. setData(data)
  60. if (props.initAfter) props.initAfter(chart)
  61. })
  62. } else {
  63. chart.setOption(props.option)
  64. if (props.initAfter) props.initAfter(chart)
  65. }
  66. }
  67. function resize() {
  68. chart.resize()
  69. }
  70. // 父组件可调用,设置动态数据
  71. function setData(option: Record<string, any>) {
  72. chart.setOption(option)
  73. }
  74. </script>
  75. <template>
  76. <div ref="wchart" :style="`width: ${props.width} ; height: ${props.height}`" />
  77. </template>
  78. <style lang="scss" scoped></style>

使用

1. 使用 echarts 普通图表

示例:使用玫瑰环形图

  1. <script setup lang="ts">
  2. import WChart from '@comp/chart/index.vue'
  3. defineOptions({
  4. name: 'ChartLoop'
  5. })
  6. // 正常 echarts 参数
  7. const option = {
  8. grid: {
  9. top: '20',
  10. left: '10',
  11. right: '10',
  12. bottom: '20',
  13. containLabel: true
  14. },
  15. series: [
  16. {
  17. name: '人口统计',
  18. type: 'pie',
  19. radius: [50, 120],
  20. center: ['50%', '50%'],
  21. roseType: 'area',
  22. itemStyle: {
  23. borderRadius: 8
  24. },
  25. label: {
  26. formatter: '{b}\n{c} 万人'
  27. },
  28. data: [
  29. { value: 2189.31, name: '北京' },
  30. { value: 1299.59, name: '西安' },
  31. { value: 1004.79, name: '长沙' }
  32. ]
  33. }
  34. ]
  35. }
  36. </script>
  37. <template>
  38. <WChart width="100%" height="300px" :option="option" />
  39. </template>
  40. <style lang="scss" scoped></style>

image

2. 结合百度地图

示例:西安热力图

  1. <script setup lang="ts">
  2. import { reactive } from 'vue'
  3. import WChart from '@comp/chart/index.vue'
  4. // 注意需要引入 bmap,即 echarts 对百度地图的支持扩展
  5. import 'echarts/extension/bmap/bmap'
  6. // 热力数据,内容如:{ features: [ { geometry: { coordinates: [ [ [x, y] ] ] } } ]}
  7. // 为什么这么复杂,因为是我从阿里地理数据下载的,地址 https://datav.aliyun.com/portal/school/atlas/area_selector
  8. import xianJson from '@/assets/xian.json'
  9. defineOptions({
  10. name: 'ChartMap'
  11. })
  12. const option = {
  13. animation: false,
  14. backgroundColor: 'transparent',
  15. bmap: {
  16. // 地图中心点
  17. center: [108.93957150268, 34.21690396762],
  18. zoom: 12,
  19. roam: true
  20. },
  21. visualMap: {
  22. show: false,
  23. top: 'top',
  24. min: 0,
  25. max: 5,
  26. seriesIndex: 0,
  27. calculable: true,
  28. inRange: {
  29. color: ['blue', 'blue', 'green', 'yellow', 'red']
  30. }
  31. },
  32. series: [
  33. {
  34. type: 'heatmap',
  35. coordinateSystem: 'bmap',
  36. data: reactive([] as any[]),
  37. pointSize: 5,
  38. blurSize: 6
  39. }
  40. ]
  41. }
  42. const initBefore = () => {
  43. return new Promise((resolve) => {
  44. // 处理数据
  45. const arr = []
  46. for (const item of xianJson.features) {
  47. const positions = item.geometry.coordinates[0][0]
  48. for (const temp of positions) {
  49. const position = temp.concat(Math.random() * 1000 + 200)
  50. arr.push(position)
  51. }
  52. }
  53. option.series[0].data = arr
  54. resolve(option)
  55. })
  56. }
  57. const initAfter = (chart: {
  58. getModel: () => {
  59. (): any
  60. new (): any
  61. getComponent: { (arg0: string): { (): any; new (): any; getBMap: { (): any; new (): any } }; new (): any }
  62. }
  63. }) => {
  64. // 添加百度地图插件
  65. var bmap = chart.getModel().getComponent('bmap').getBMap()
  66. // 百度地图样式,需要自己去创建
  67. bmap.setMapStyleV2({
  68. styleId: 'bc05830a75e51be40a38ffc9220613bb'
  69. })
  70. // bmap.addControl(new BMap.MapTypeControl())
  71. }
  72. </script>
  73. <template>
  74. <WChart width="100%" height="500px" :option="option" :initBefore="initBefore" :initAfter="initAfter" />
  75. </template>
  76. <style lang="scss" scoped></style>

image

原文链接:https://www.cnblogs.com/weizwz/p/17933635.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号