父组件
<template>
<div>
<Chart :option="chartOption" style="height: 400px" />
</div>
</template>
<script>
import Chart from "../../components/Chart";
import random from "lodash/random";
export default {
components: {
Chart,
},
data() {
return {
chartOption: {
title: {
text: "ECharts",
},
tooltip: {},
legend: {
data: ["销量"],
},
xAxis: {
data: [
"衬衫",
"羊毛衫",
"雪纺衫",
"裤子",
"高跟鞋",
"袜子",
],
},
yAxis: {},
series: [
{
name: "销量",
type: "bar",
data: [5, 20, 36, 10, 10, 20],
},
],
},
};
},
mounted() {
this.interVal = setInterval(() => {
this.chartOption.series[0].data = this.chartOption.series[0].data.map(
() => random(100)
);
this.chartOption = { ...this.chartOption }; // 监听option 手动让 chartOption 变成新值
}, 6000);
},
beforeDestroy() {
clearInterval(this.interVal);
},
};
</script>
子组件
<template>
<div ref="chartdDom"></div>
</template>
<script>
import echarts from "echarts";
import { addListener, removeListener } from "resize-detector"; // echarts 高度宽度 适应
import debounce from "lodash/debounce";
export default {
props: {
option: {
type: Object,
default: () => {},
},
},
watch: {
option(val) {
this.chart.setOption(val);
},
},
created() {
// 防抖
this.resize = debounce(this.resize, 300);
},
mounted() {
// 基于准备好的dom,初始化echarts实例
this.chart = echarts.init(this.$refs.chartdDom);
addListener(this.$refs.chartdDom, this.resize);
// 使用刚指定的配置项和数据显示图表。
this.renderChart();
},
beforeDestroy() {
removeListener(this.$refs.chartdDom, this.resize);
// 释放图表销毁对象并设为空
this.chart.dispose();
this.chart = null;
},
methods: {
resize() {
console.log("this");
this.chart.resize();
},
renderChart() {
this.chart.setOption(this.option);
},
},
};
</script>