在 vue 中使用 echarts 图步骤:安装 echarts 库引入 echarts创建 echarts 实例设置图表选项更新图表销毁图表
Vue 中 ECharts 图的使用
在 Vue 中使用 ECharts 图非常简单,只需要以下几个步骤:
1. 安装 ECharts 库
npm install --save echarts
2. 引入 ECharts
在你的 Vue 组件中,导入 ECharts:
import * as echarts from 'echarts';
3. 创建 ECharts 实例
在 mounted() 生命周期钩子里,创建一个 ECharts 实例并将其附加到 DOM 元素:
mounted() {
this.chart = echarts.init(this.$refs.chart);
}
其中,this.$refs.chart 是你用于渲染图表的 DOM 元素的 ref。
4. 设置图表选项
使用 setOption() 方法设置图表选项:
this.chart.setOption({
title: {
text: '图表标题'
},
series: [{
type: 'line',
data: [1, 2, 3, 4, 5]
}]
});
5. 更新图表
当数据更新时,可以调用 setOption() 方法更新图表:
this.chart.setOption({
series: [{
data: [6, 7, 8, 9, 10]
}]
});
6. 销毁图表
在 beforeDestroy() 生命周期钩子里,销毁图表:
beforeDestroy() {
this.chart.dispose();
}
示例
<template><div ref="chart"></div>
</template><script>
import * as echarts from 'echarts';
export default {
mounted() {
this.chart = echarts.init(this.$refs.chart);
this.chart.setOption({
title: {
text: '图表标题'
},
series: [{
type: 'line',
data: [1, 2, 3, 4, 5]
}]
});
},
beforeDestroy() {
this.chart.dispose();
}
};
</script>