MutationObserver无法监听宽度变化,使用vue自定义指令

在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" />
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值