首先在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) } }