關於VUE監聽視窗變化事件問題
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 = function() {
return function(){
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)
}
}
}
最後一步: 去看看你想要的結果吧~