问题重现
在Vue2中学习使用eCharts时遇到了如下问题:
使用eCharts提供的resize()方法,监听图表容器的大小并改变图表大小。
我在组件中这样写:
export default {
name: "chart",
data() {
return {
chart: null,
};
},
methods: {
initChart() {
this.chart = echarts.init(document.getElementById("Chart1"));
this.chart.setOption({
// https://echarts.apache.org/zh/option.html#title.text
// ...
});
},
},
mounted() {
this.initChart();
// 监听 resize 事件
window.addEventListener("resize", function () {
this.chart.resize();
});
},
};
在浏览器改变窗口后,控制台报错:
Uncaught TypeError: Cannot read properties of undefined (reading 'resize')
解决
会出现这样的情况,其实是js中的this
指向问题,把事件触发时执行的函数改为箭头函数
即可解决。
window.addEventListener("resize", () => {
this.chart.resize();
});