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)
}
}
}
最后一步: 去看看你想要的結果吧~
方案二:
在vue 2.x 里面的時候,可以在 mounted 鈎子中 全局監聽 resize 事件,然后綁定的函數再做具體的處理。
也是親測有效,比之前的方法會好很多。