赞
踩
你可以使用Vue的指令v-on和v-bind来动态监听div的宽度。
首先,在Vue实例中声明一个data属性,用来存储div的宽度值。例如:
data() {
return {
divWidth: null, // 存储div的宽度
}
}
然后,在div元素上使用v-bind将div的宽度绑定到data属性divWidth上,并使用v-on指令监听window的resize事件,当窗口大小发生变化时更新div的宽度值。如下所示:
<template> <div> <div ref="myDiv" :style="{ width: divWidth + 'px' }"></div> </div> </template> <script> export default { data() { return { divWidth: null, } }, mounted() { // 在mounted钩子函数中获取div的初始宽度 this.divWidth = this.$refs.myDiv.offsetWidth; // 监听窗口的resize事件,更新div的宽度 window.addEventListener('resize', this.updateDivWidth); }, methods: { updateDivWidth() { this.divWidth = this.$refs.myDiv.offsetWidth; } }, beforeDestroy() { // 在组件销毁前,移除resize事件监听 window.removeEventListener('resize', this.updateDivWidth); }, } </script>
directives: { // 使用局部注册指令的方式 resize: { // 指令的名称 bind(el, binding) { // el为绑定的元素,binding为绑定给指令的对象 let width = '', height = ''; function isReize() { const style = document.defaultView.getComputedStyle(el); if (width !== style.width || height !== style.height) { binding.value(); // 关键 } width = style.width; height = style.height; } el.__vueSetInterval__ = setInterval(isReize, 300); }, unbind(el) { clearInterval(el.__vueSetInterval__); } } }
在html中使用:
<div v-resize="resize"></div> // 绑定的resize是一个函数
//在methods中
resize() { // 当宽高变化时就会执行
//执行某些操作
}
当然可以结合一下1和2 这里就不做演示了。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。