相关链接: 官网:echarts.apache.org/handbook/zh…
官方示例:echarts.apache.org/examples/zh…
官方配置项文档:echarts.apache.org/zh/option.h…
分享素材库:chart.majh.top/ (这里常见的echarts图表类型基本上都可以找到)
使用:
1 项目中引入
npm install echarts --save
2 项目中使用 项目中需多次使用echarts时,可将其封装为组件,通过配置项传参进行引入.
假设组件名为echarts.vue,在该文件中
1 添加echarts图表的渲染容器.
<template>
<div class="chartContainer">
<div class="echart" ref="echart"></div>
</div>
</template>
2 设置渲染容器的宽高
<style lang="scss" scoped>
.chartContainer {
width: 100%;
.echart {
width: 100%;
height: 100%;
}
}
</style>
3 js部分--引入并设置配置项
<script>
//引入echarts对象
import * as echarts from "echarts";
export default {
name: "Chart",
props: ["option"],
data() {
return {
myChart: null,
};
},
methods: {
initCharts() {
this.$nextTick(() => {
this.myChart = echarts.init(this.$refs.echart);//获取渲染容器
this.myChart.setOption(this.option);//使用传入的配置项配置图表
this.myChart.resize();//图表随屏幕进行缩放
window.addEventListener("resize", this.chartsResize);
});
},
chartsResize() {
this.myChart && this.myChart.resize();
},
},
mounted() {
this.initCharts();
},
};
</script>
4 需要对传入的配置项进行监视,当配置项数据进行更新时,需要重绘图表.
watch: {
option: {
deep: true,
handler: function (v) {
this.myChart && this.myChart.clear();
this.myChart && this.myChart.setOption(v);
this.myChart && this.myChart.resize();
},
},
},
5 组件销毁前清除echarts对象
beforeDestroy() {
if (this.myChart) {
window.removeEventListener("resize", this.chartsResize);
this.myChart = null;
this.myChart.clear();
}
},