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)
}
}
我其实也有努力呀

浙公网安备 33010602011771号