当前位置:   article > 正文

Vue--监听元素宽高变化_vue监听某个元素宽度的改变

vue监听某个元素宽度的改变

解决方案

1、使用element-resize-detector插件
2、使用自定义指令

element-resize-detector插件

npm install element-resize-detector

自定义指令
<template>
  <transition>
    <div v-resize="DomResize">
    </div>
  </transition>
</template>
<script>
export default {
  directives: {
    resize: {
      // 指令的名称
      bind(el, binding) {
        // el为绑定的元素,binding为绑定给指令的对象
        // console.log(el, '绑定', binding)
        let width = ''
        let height = ''
        function isResize() {
          const style = document.defaultView.getComputedStyle(el)
          if (width !== style.width || height !== style.height) {
            binding.value({ width: style.width, height: style.height }) // 关键(这传入的是函数,所以执行此函数)
          }
          width = style.width
          height = style.height
        }
        el.__vueSetInterval__ = setInterval(isResize, 300)
      },
      unbind(el) {
        // console.log(el, '解绑')
        clearInterval(el.__vueSetInterval__)
      }
    }
  },
  methods:{
    DomResize(data) {
      // const { width, height } = data
      // console.log('width:', width, 'height:', height, '   dom尺寸方式改变')
    }
  }
}
</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/223150
推荐阅读
相关标签