封装看1 不封装看2
1.封装自适应文件
echartsResize.js
// 防抖函数
export default function debounce(fn, delay) {
let timer = null
return function () {
// 获取函数的作用域和变量
const context = this
const args = arguments
clearTimeout(timer)
timer = setTimeout(function () {
fn.apply(context, args)
}, delay)
}
}
组件引用
// 引用
import chartResize from '@/utils/echartsResize'
mounted() {
// 监听浏览器窗口变化
window.addEventListener('resize', this.handleResize)
},
beforeDestroy() {
// 销毁监听事件
window.removeEventListener('resize', this.handleResize)
},
methods: {
// echarts防抖重绘
handleResize: chartResize(function () {
// 重绘
this.charts.resize()
}, 300),
}
2.不封装直接使用
<template>
<div>
<!-- some content -->
</div>
</template>
<script>
export default {
data() {
return {
timeout: 0,
};
},
mounted() {
window.addEventListener('resize', this.handleResize);
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
},
methods: {
debounce(func, wait) {
clearTimeout(this.timeout);
this.timeout = setTimeout(func, wait);
},
handleResize() {
this.debounce(() => {
// 在此操作节流重绘
console.log('Resized!');
}, 300);
},
},
};
</script>