VueJs監聽window.resize方法樣本,vuejswindow.resize

來源:互聯網
上載者:User

VueJs監聽window.resize方法樣本,vuejswindow.resize

Vuejs 本身就是一個 MVVM 的架構。

但是在監聽 window 上的 事件 時,往往會顯得 力不從心。

比如 這次是 window.resize

恩,我做之前也是百度了一下。看到大傢伙都為這個問題而發愁。

問題: 今天我也 遇到了這樣一個問題, 是關於canvas 自適應。 根據視窗的變化去變化 canvas 的寬度

備忘: 重要的問題說三遍 解決 架構內的bug 先說 架構 版本 版本 版本 (這裡用的 Vue 2.x 、ES6)

解決方案:

第一步: 先在 data 中去 定義 一個記錄寬度是 屬性

data: { screenWidth: document.body.clientWidth // 這裡是給到了一個預設值 (這個很重要)}

第二步: 我們需要 講 reisze 事件在 vue mounted 的時候 去掛載一下它的方法

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

第三步: watch 去監聽這個 屬性值的變化,如果發生變化則講這個val 傳遞給 this.screenWidth

  watch: {   screenWidth (val) {    this.screenWidth = val   }  }

第四步:最佳化 因為 頻繁 觸發 resize 函數,導致頁面很卡的 問題

  watch: {   screenWidth (val) {    if (!this.timer) {     this.screenWidth = val     this.timer = true     let that = this     setTimeout(function () {      // that.screenWidth = that.$store.state.canvasWidth      console.log(that.screenWidth)      that.init()      that.timer = false     }, 400)    }   }  }

最後一步: 去看看你想要的結果吧~

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.