Vuejs 本身就是一個 MVVM 的框架。但是在監(jiān)聽 window 上的 事件 時,往往會顯得 力不從心。
比如 這次是 window.resize恩,我做之前也是百度了一下。看到大家伙都為這個問題而發(fā)愁。
問題: 今天我也 遇到了這樣一個問題, 是關(guān)于canvas 自適應(yīng)。 根據(jù)窗口的變化去變化 canvas 的寬度備注: 重要的問題說三遍 解決 框架內(nèi)的bug 先說 框架 版本 版本 版本 (這里用的 Vue 2.x 、ES6)
解決方案:
第一步: 先在 data 中去 定義 一個記錄寬度是 屬性
data: { screenWidth: document.body.clientWidth // 這里是給到了一個默認值 (這個很重要) }第二步: 我們需要 講 reisze 事件在 vue mounted 的時候 去掛載一下它的方法
mounted () { const that = this window.onresize = function() { return function(){ window.screenWidth = document.body.clientWidth; that.screenWidth = window.screenWidth })() } }第三步: watch 去監(jiān)聽這個 屬性值的變化,如果發(fā)生變化則講這個val 傳遞給this.screenWidth
watch: { screenWidth (val) { this.screenWidth = val } }第四步:優(yōu)化 因為 頻繁 觸發(fā) resize 函數(shù),導(dǎo)致頁面很卡的 問題
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) } } }最后一步: 去看看你想要的結(jié)果吧~
以上這篇淺談VUE監(jiān)聽窗口變化事件的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持武林網(wǎng)。
新聞熱點
疑難解答