在VUE项目中碰到需要监听DOM元素长宽变化时,自动更新图的功能。有人可能说,直接监听window的resize不就可以了么。
window.addEventListener('resize', (event) => { // function here })
上述确实可以解决很多问题,但是楼主遇到的问题要是这么简单可就太好了。当时的场景是浏览器长宽没有变化,但是图表长宽变化了。图表定长,宽度使用百分比自适应,代码如下:
<div ref="chart" class="chart" id="chart" />
.chart {
width: 100%;
height: 200px;
}
当时的第一反应是使用MutationObserver监听attributes变化
const observer = new MutationObserver(callback);
const chartDom = document.querySelector('chart');
observer.observer(article, {
arrtibutes: true, // attributes of node
attributeFilter:['style'], // an array of attribute names, to observe only selected ones.
attributeOldValue:true. // if true, pass both the old and the new value of node.data to callback (see below), otherwise only the new one (needs characterData option)
});
funtion callback() {
// function here
console.log('resize');
}
但是由于图标的class中使用百分比自动适配,并没有更改style中的属性,所以一直没有监听到变化。
一路不行再换一路,VUE的指令可以直接拿到dom信息,话不多说了直接上代码
import { DirectiveOptions } from 'vue';
const resize: DirectiveOptions = {
bind(el, binding) {
// 记录长宽
let width = '';
let height = '';
function getSize() {
const style = (document.defaultView as any).getComputedStyle(el);
// 如果当前长宽和历史长宽不同
if (width !== style.width || height !== style.height) {
// binding.value在这里就是下面的resizeChart函数
binding.value({ width, height });
}
width = style.width;
height = style.height;
}
(el as any).__vueDomResize__ = setInterval(getSize, 500);
},
unbind(el) {
clearInterval((el as any).__vueDomResize__);
},
};
export default resize;
<div ref="chart" class="chart" v-resize="resizeChart" />