思路:在data里获取当前屏幕的宽和建立一个定时器,在mounted钩子函数里监听窗口大小
watch监听data里的当前屏幕然后进行调用methods方法 销毁组件的时候清除定时器
tip:在methods里加上resize()方法
<div id="Column"></div>
data(){
screenWidth:document.body.clientWidth, // 屏幕宽度
timer: null, //设置一个定时器
},
mounted () {
// 监听窗口大小
window.onresize = () => {
return (() => {
this.screenWidth = document.body.clientWidth
})()
}
},
watch:{
screenWidth(val) {
// 为了避免频繁触发resize函数导致页面卡顿
if (!this.timer) {
// 监听screenWidth值改变,就将其重新赋给screenWidth
this.screenWidth = val;
this.timer = true;
let that = this;
setTimeout(function () {
that.setCylinder(); //(调用图表的方法)
that.timer = false;
}, 300);
}
},
}
mounted(){
//Echarts实例
setCylinder() {
var CylinderEcharts = this.$echarts.init(document.getElementById("Column"));
………………
CylinderEcharts.setOption(CylinderOption);
CylinderEcharts.resize();
},
}
// 销毁定时器
destroyed() {
clearInterval(this.timer);
this.timer= null;
},