1. 程式人生 > 其它 >vue使用自定義指令監聽元件寬高變化

vue使用自定義指令監聽元件寬高變化

自定義指令程式碼

 directives: { // 使用區域性註冊指令的方式
    resize: { // 指令的名稱
      bind (el, binding) { // el為繫結的元素,binding為繫結給指令的物件
        let width = ''
        let 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__) } }

標籤上使用:div
<div :class="[$options.name]" ref="databaseCon" v-resize="resize"></div>


在method中定義方法,通過原生window中的getComputedStyle獲取元素的css樣式屬性:

window.getComputedStyle(el, null)[attribute]