Vue实现监听dom节点宽高变化

在Vue中实现监听dom节点宽高变化

原生js方法

该方法适用所有vue项目,原生js开发的思维

	
mounted(){
		// 监听节点宽高变小
		(this.$refs.scroll as HTMLElement).scrollTop = 1000;
        (this.$refs.scroll as HTMLElement).scrollLeft = 1000;
        (this.$refs.scroll as HTMLElement).addEventListener('scroll', () => {
            this.width = ((this.$refs.datas as Vue).$el as HTMLElement).offsetWidth;
            (this.$refs.scroll2 as HTMLElement).scrollTop = 1000;
            (this.$refs.scroll2 as HTMLElement).scrollLeft = 1000;
        });
        
		// 监听节点宽高变大
        (this.$refs.scroll2 as HTMLElement).scrollTop = 1000;
        (this.$refs.scroll2 as HTMLElement).scrollLeft = 1000;
        (this.$refs.scroll2 as HTMLElement).addEventListener('scroll', () => {
            this.width = ((this.$refs.datas as Vue).$el as HTMLElement).offsetWidth;
            (this.$refs.scroll as HTMLElement).scrollTop = 1000;
            (this.$refs.scroll as HTMLElement).scrollLeft = 1000;
        })
}

element-ui element-resize-detector插件

vue + element 开发项目时的首选,简单有效

<div ref="datas"></div>
mounted(){
	    let erd = elementResizeDetectorMaker();
        erd.listenTo((this.$refs.datas as Vue).$el,  (element: HTMLElement) => {
            this.width = element.offsetWidth;
        })
}

你可能感兴趣的:(vue)