頁面開啟監聽后 記得要銷毀

案例: 我做了個 圖表自適應
<template>
<div>
<a-row style="margin: 20px">
<a-col>
<div
id="container"
v-bind:style="{ width: size, height: height }"
></div>
</a-col>
</a-row>
<hr />
</div>
</template>
<script>
import echarts from "echarts";
export default {
props: {
datalist: {
type: Array,
},
},
data() {
return {
size: "110%",
height: "300px",
screenWidth: "",
screenHeight: "",
// charts: null
};
},
mounted() {
this.screenWidth = document.body.clientWidth;
this.screenHeight = document.body.clientHeight;
//這里是監控瀏覽器變大 或者 縮放 ,當有變化時,會觸發showChart()函數里面的charts.resize();//重新適配大小
window.addEventListener(
"resize",
this.resizeFunc,
false
);
},
watch: {
datalist: function () {
this.showChart();
},
},
methods: {
resizeFunc () {
this.screenWidth = document.body.clientWidth;
this.screenHeight = document.body.clientHeight;
this.showChart();
},
showChart() {
// 基於准備好的dom,初始化echarts實例
var charts = echarts.init(document.getElementById("container"), "light");
// 指定圖表的配置項和數據
var option = {
grid: {
// 控制圖的大小,調整下面這些值就可以,
y: 40, //控制x軸文字與底部的距離
x: 30, //控制y軸文字與左邊的距離
},
title: {
text: "本周新增用例數",
},
tooltip: {},
legend: {},
xAxis: {
//底部字橫着放
axisLabel: {
margin: 10,
interval: 0, //橫軸信息全部顯示
rotate: -15, //-15度角傾斜顯示
},
data: this.datalist[0],
},
yAxis: {
type: "value",
//控制y軸間隔單位
minInterval: 1,
},
series: [
{
name: "",
type: "bar",
data: this.datalist[1],
},
],
};
// 使用剛指定的配置項和數據顯示圖表。
charts.setOption(option);
charts.resize(); //重新適配大小
},
},
#離開頁面銷毀監聽
destroyed() {
window.removeEventListener('resize', this.resizeFunc)
}
};
</script>
<style scoped>
</style>
