vue.js監聽瀏覽器窗口寬度變化


首先在data中定義要監聽的屬性,因為watch偵聽器監聽的是data中的屬性,不能直接監聽window

export default {
 data () {
    return {
         creenWidth: document.body.clientWidth,
   }
  }
}

 在mouted當中調用window.onresize()事件,onresize事件會在窗口或框架被調整大小時觸發

const that = this
    window.onresize= () => {
      return (() => {
        window.screenWidth = document.body.clientWidth;
        that.screenWidth = window.screenWidth;
      })();
    }

我在寫window.onresize的時候發現這個事件有時候並不會觸發,所以我又另找了一種,

 const that = this
    window.addEventListener("resize", function() {
      return (() => {
        window.screenWidth= document.body.clientWidth;
        that.screenWidth= window.screenWidth;
      })();
    });

最后在watch監聽data中的creenWidth屬性就可以了

 screenWidth: {
      immediate: true,
      handler(newValue) {
       console.log(newValue)
      }
    }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM