1. 程式人生 > 其它 >vue 監聽頁面 元素寬度和高度 變化 可以傳參 自定義指令(區域性)

vue 監聽頁面 元素寬度和高度 變化 可以傳參 自定義指令(區域性)

vue 監聽頁面 元素寬度和高度(我值監聽了寬度) 變化

外掛安裝 element-resize-detector


    npm install element-resize-detector

引入外掛

要是有用餓了麼UI框架的話,這個都不用引入
<script>
import elementResizeDetectorMaker from "element-resize-detector";
</script>

註冊區域性自定義指令

 ![](https://img2020.cnblogs.com/blog/1830100/202107/1830100-20210722191920382-1343319426.png)


 directives: {
    // 使用區域性註冊指令的方式
    resize: {
      // 指令的名稱
      bind(el, binding, vnode) {
        // el為繫結的元素,binding為繫結給指令的物件
        let width = "";
        // let height = "";  這就是監聽高度了
        let that = vnode.context;
        function isReize() {
          const style = document.defaultView.getComputedStyle(el);
          // if (width !== style.width||height !== style.height) {  這就是監聽寬度和高度了
          if (width !== style.width) {
            // binding.value();  // 關鍵
            let pxNumber = style.width.split("px")[0];
            that[binding.arg](binding.value, pxNumber);
          }
          width = style.width;
          // height = style.height;  這就是監聽寬度和高度了
        }
        el.__vueSetInterval__ = setInterval(isReize, 300);
      },
      unbind(el) {
        clearInterval(el.__vueSetInterval__);
      },
    },
  },

行間繫結 (繫結要監聽的元素)


<div   v-resize:resize="{
              className: index + 'titleContent',
            }"></div>

事件操作 (元素寬度改變時執行的事件)


 /**
     * @description: 監聽寬度的改變事件   自定義指令 CDMB0000212titleContent
     * @param {*} value
     * @param {*} width
     * @return {*}
     */
    resize(value, width) {
      //value 這個是傳進來的引數的物件  //{className:"0000titleContent"}   上面的變數index值是0000
       // width是寬度的值 
      if (value && value.className) {
        if (width < 800) {
          //$("." + value.className).hide();
        } else {
          //$("." + value.className).show();
        }
      }
    }