Vue——全局element-resize-detector監(jiān)聽DOM元素

相信很多用ele做pc端平臺的很多小伙伴都遇到過這樣一個(gè)問題,就是在做側(cè)邊欄菜單時(shí),會有一個(gè)收縮和展開的一個(gè)功能。

這就導(dǎo)致了一個(gè)問題,那就是在我門伸縮的過程中。右邊的主題頁面的寬度就會隨之改變。

我上網(wǎng)查了查 ,也動手試了試這個(gè) window.onresize = ()=>{}。卻不盡人意,因?yàn)?/p>

他只能檢測瀏覽器大小的變化,完全跟我們的需求不沾邊。經(jīng)過我的不屑怒力,

終于找到了解決的方法。

這是我所看到的原創(chuàng)作者的分享:

https://shentuzhigang.blog.csdn.net/article/details/107881057

第一步 通過npm install element-resize-detector獲取elementResizeDetectorMaker

npm install element-resize-detector

第二步:將依賴引入import elementResizeDetectorMaker from ‘element-resize-detector’ (main.js中)

import ElementResizeDetectorMaker from "element-resize-detector"
Vue.prototype.$erd = ElementResizeDetectorMaker()

第三步:使用(這里的東西是不完整的旨在能讓你們看懂)

<template>
  <div class="index">
    <div class="left"></div>
    <div class="right" :style="
        'width:calc(100% - (' +
        width +
        'px));height:' +
        height +
        'px'
      "></div> 
  </div>
</template>

<script>
export default {
  data() {
    return {
      width: "",
      height: "",
    };
  },
  mounted() {
    this.$erd.listenTo(document.querySelector(".left"), (element) => {
      this.width = element.offsetWidth;
      this.height = element.offsetHeight;
      // 這里就能隨時(shí)打印出來.left的寬和高了
      console.log('width'+this.width,'height'+this.height)  
    });
  },
};
</script>

<style>
</style>

以上就是element-resize-detector的引入和監(jiān)聽了
如果這篇文章對你有幫助,或者在進(jìn)行中遇到其他問題,歡迎評論區(qū)留言出來。
我們一起探討~

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容