首页 > 其他分享 >vue3+ts打开echarts的正确方式

vue3+ts打开echarts的正确方式

时间:2023-12-28 21:47:50浏览次数:31  
标签:const option props chart ts bmap vue3 echarts

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

准备工作

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

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

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

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

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

3. 安装 echarts

npm i echarts -S

封装

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

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

module.exports = {
  // 其他省略
  globals: {
    BMap: true
  }
}

2. 全局注册 echarts

修改 main.ts

// 引入 echarts
import * as echarts from 'echarts'
import themeJSON from '@/assets/weizwz.json'
echarts.registerTheme('weizwz', themeJSON)

const app = createApp(App)
// 全局挂载 echarts
app.config.globalProperties.$echarts = echarts

3. 封装 echarts

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

<script setup lang="ts">
import { onMounted, getCurrentInstance, defineExpose, ref } from 'vue'

defineOptions({
  name: 'WChart'
})
// defineExpose 让父组件可调用此方法
defineExpose({
  setData
})

// 组件传参
const props = defineProps({
  width: {
    type: String, //参数类型
    default: '100%', //默认值
    required: false //是否必须传递
  },
  height: {
    type: String,
    default: '10rem',
    required: true
  },
  option: {
    type: Object,
    default: () => {
      return {}
    },
    required: true
  },
  // 初始化之前的工作,比如加载百度地图相关数据
  initBefore: {
    type: Function,
    required: false
  },
  // 初始化之后的工作,比如添加百度地址控件
  initAfter: {
    type: Function,
    required: false
  }
})

let chart: { setOption: (arg0: Record<string, any>) => void; resize: () => void }
const wchart = ref(null)

//声明周期函数,自动执行初始化
onMounted(() => {
  init()
  // 监控窗口大小,自动适应界面
  window.addEventListener('resize', resize, false)
})

//初始化函数
function init() {
  // 基于准备好的dom,初始化echarts实例
  const dom = wchart.value
  // 通过 internalInstance.appContext.config.globalProperties 获取全局属性或方法
  let internalInstance = getCurrentInstance()
  let echarts = internalInstance?.appContext.config.globalProperties.$echarts

  chart = echarts.init(dom, 'weizwz')
  // 渲染图表
  if (props.initBefore) {
    props.initBefore(chart).then((data: Record<string, any>) => {
      setData(data)
      if (props.initAfter) props.initAfter(chart)
    })
  } else {
    chart.setOption(props.option)
    if (props.initAfter) props.initAfter(chart)
  }
}

function resize() {
  chart.resize()
}
// 父组件可调用,设置动态数据
function setData(option: Record<string, any>) {
  chart.setOption(option)
}
</script>

<template>
  <div ref="wchart" :style="`width: ${props.width} ; height: ${props.height}`" />
</template>

<style lang="scss" scoped></style>

使用

1. 使用 echarts 普通图表

示例:使用玫瑰环形图

<script setup lang="ts">
import WChart from '@comp/chart/index.vue'

defineOptions({
  name: 'ChartLoop'
})
// 正常 echarts 参数
const option = {
  grid: {
    top: '20',
    left: '10',
    right: '10',
    bottom: '20',
    containLabel: true
  },
  series: [
    {
      name: '人口统计',
      type: 'pie',
      radius: [50, 120],
      center: ['50%', '50%'],
      roseType: 'area',
      itemStyle: {
        borderRadius: 8
      },
      label: {
        formatter: '{b}\n{c} 万人'
      },
      data: [
        { value: 2189.31, name: '北京' },
        { value: 1299.59, name: '西安' },
        { value: 1004.79, name: '长沙' }
      ]
    }
  ]
}
</script>

<template>
  <WChart width="100%" height="300px" :option="option" />
</template>

<style lang="scss" scoped></style>

image

2. 结合百度地图

示例:西安热力图

<script setup lang="ts">
import { reactive } from 'vue'
import WChart from '@comp/chart/index.vue'
// 注意需要引入 bmap,即 echarts 对百度地图的支持扩展
import 'echarts/extension/bmap/bmap'
// 热力数据,内容如:{ features: [ { geometry: { coordinates: [ [ [x, y] ] ] } } ]}
// 为什么这么复杂,因为是我从阿里地理数据下载的,地址 https://datav.aliyun.com/portal/school/atlas/area_selector
import xianJson from '@/assets/xian.json'

defineOptions({
  name: 'ChartMap'
})

const option = {
  animation: false,
  backgroundColor: 'transparent',
  bmap: {
    // 地图中心点
    center: [108.93957150268, 34.21690396762],
    zoom: 12,
    roam: true
  },
  visualMap: {
    show: false,
    top: 'top',
    min: 0,
    max: 5,
    seriesIndex: 0,
    calculable: true,
    inRange: {
      color: ['blue', 'blue', 'green', 'yellow', 'red']
    }
  },
  series: [
    {
      type: 'heatmap',
      coordinateSystem: 'bmap',
      data: reactive([] as any[]),
      pointSize: 5,
      blurSize: 6
    }
  ]
}

const initBefore = () => {
  return new Promise((resolve) => {
    // 处理数据
    const arr = []
    for (const item of xianJson.features) {
      const positions = item.geometry.coordinates[0][0]
      for (const temp of positions) {
        const position = temp.concat(Math.random() * 1000 + 200)
        arr.push(position)
      }
    }
    option.series[0].data = arr
    resolve(option)
  })
}

const initAfter = (chart: {
  getModel: () => {
    (): any
    new (): any
    getComponent: { (arg0: string): { (): any; new (): any; getBMap: { (): any; new (): any } }; new (): any }
  }
}) => {
  // 添加百度地图插件
  var bmap = chart.getModel().getComponent('bmap').getBMap()
  // 百度地图样式,需要自己去创建
  bmap.setMapStyleV2({
    styleId: 'bc05830a75e51be40a38ffc9220613bb'
  })
  // bmap.addControl(new BMap.MapTypeControl())
}
</script>

<template>
  <WChart width="100%" height="500px" :option="option" :initBefore="initBefore" :initAfter="initAfter" />
</template>

<style lang="scss" scoped></style>

image

标签:const,option,props,chart,ts,bmap,vue3,echarts
From: https://www.cnblogs.com/weizwz/p/17933635.html

相关文章

  • flink中的setStreamTimeCharacteristic 指定为EventTime的source需要自己定义event ti
    flink中的setStreamTimeCharacteristicTimeCharacteristic   env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime) 此处可以取以下三类值:EventTime事件时间,事件(Event)本身的时间,即数据流中事件实际发生的时间,通常使用事件发生时的时间戳来描述,这些......
  • 通达OA 任意文件上传+文件包含 getshell
    漏洞影响版本通达OAV11版<=11.320200103通达OA2017版<=10.1920190522通达OA2016版<=9.1320170710通达OA2015版<=8.1520160722通达OA2013增强版<=7.2520141211通达OA2013版<=6.2020141017漏洞分析根据网上的文章可以知道任意文件上传的漏洞点在is......
  • vue3+lottie实现动画
    1、安装lottie-webnpmilottie-web2、使用在线json文件<template><divclass="box"><divid="lottie_box"style="width:800px;height:800px;margin-left:1000px;background-color:pink"></div><butt......
  • PTS 3.0:可观测加持的下一代性能测试服务
    作者:肖长军(穹谷)大家好,我是来自阿里云云原生应用平台的肖长军,花名穹谷,我此次分享的主题是《可观测加持的下一代性能测试服务》。提到性能测试大家并不陌生,性能测试已成为评估系统能力、识别系统弱点、进行系统调优,验证系统稳定性等的重要手段。我们一般进行性能测试的大概流程就是构......
  • HighCharts 地图画航线,以及在城市点画圈
    需求:生成一个世界地图,在城市点处画一个响应式的圈,及在城市点间画一条指示性的航线分析:生成一幅世界地图需导入相关地图js文件与获取json文件,在城市点画一个响应式的圈和一条指示性的航线,需要生成序列,并指定类型,航线类型(flowmap),响应式的圆圈用render进行画圆圈,具体请看下图解决:源......
  • TSINGSEE青犀智能分析网关V4在智慧小区场景中的应用
    一、方案背景随着物联网、AI、大数据、5G、边缘计算、移动互联网等新兴技术的不断成熟和应用,社区作为汇聚科技社会人、房、车三大物联网时代最核心的要素,其价值将不言而喻。建设智慧小区需要充分发挥信息技术在社区管理中的作用,提高居民生活的便利性和安全性,例如建设和利用视频监......
  • PTS 3.0:可观测加持的下一代性能测试服务
    作者:肖长军(穹谷)大家好,我是来自阿里云云原生应用平台的肖长军,花名穹谷,我此次分享的主题是《可观测加持的下一代性能测试服务》。提到性能测试大家并不陌生,性能测试已成为评估系统能力、识别系统弱点、进行系统调优,验证系统稳定性等的重要手段。我们一般进行性能测试的大概流程就......
  • 海康华为大华宇视等摄像头以及各种直播流地址(RTSP/RTMP/FLV/HLS等)通过LiveNVR转成标准
    @目录1、背景说明2、通道配置2.1、直播流地址配置2.2、配置RTSP接入2.3、配置Onvif接入2.4、配置SDK接入2.4.1、海康SDK接入2.4.2、大华SDK接入2.4.3、天地伟业SDK接入2.5、配置拉转视频文件2.6、海康ISUP接入2.6.1、海康ISUP接入配置2.6.2、海康设备接入2.6.2.1、海康EHOME接......
  • 封装一个表情包组件(支持自定义表情图片)(基于vue3语法)
    效果图文件图直接贴代码emotion.vue<template><divclass="emotion-containerbeauty-scroll-livechat"><divclass="emotion-btn"@click="toggleEmotionShow"><spanclass="iconfonticon-biaoqing1&quo......
  • TSINGSEE青犀智能分析网关V4智慧工地解决方案
    一、方案背景科技高速发展的今天,工地施工已发生翻天覆地的变化,传统工地管理模式很容易造成工地管理混乱、安全事故、数据延迟等问题,人力资源的不足也进一步加剧了监管不到位的局面,严重影响了施工进度质量和安全。并且,施工工地建筑工程体量大、工地环境复杂、人员管理难度大、工地......