1 安装 ECharts
npm install echarts --save
2 全局引入
import echarts from "echarts";
Vue.prototype.$echarts = echarts;
3 将 Echarts 封装成组件
src/components/Echarts/Echarts.vue
<template>
<div ref="chartDom"></div>
</template>
<script>
import * as echarts from 'echarts'
import debounce from 'lodash/debounce'
import { addListener, removeListener } from 'resize-detector'
export default {
props: {
option: {
type: Object,
default: () => {
}
}
},
watch: {
// option(val) {
// this.chart.setOption(val);
// },
option: {
handler(val) {
this.chart.setOption(val)
},
deep: true
}
},
created() {
this.resize = debounce(this.resize, 300)
},
mounted() {
this.renderChart()
addListener(this.$refs.chartDom, this.resize)
},
beforeDestroy() {
removeListener(this.$refs.chartDom, this.resize)
this.chart.dispose()
this.chart = null
},
methods: {
resize() {
this.chart.resize()
},
renderChart() {
this.chart = echarts.init(this.$refs.chartDom)
this.chart.setOption(this.option)
}
}
}
</script>
4 到 Echarts 官网找需要的图
Echart官网 https://echarts.apache.org/zh/index.html
5 使用
将 option 拷贝至需要使用 echarts 的页面
引入组件
<Echarts :option="option" style="height: 400px;width: 630px"/>
完成