<script>
export default {
data() {
return {
screenWidth: document.body.clientWidth
};
},
watch: {
screenWidth(newVal) {
console.log('newVal', newVal);
// console.log('old', old);
// this.boxWscreenWidthidth = document.body.clientWidth;
// console.log('new', this.boxWidth);
}
},
mounted() {
const that = this;
window.onresize = () => {
window.screenWidth = document.body.clientWidth;
that.screenWidth = window.screenWidth;
};
// console.log('that.screenWidth',that.screenWidth)
}
};
</script>
先定义data中一个screenwidth属性,然后这个时候我们可以用watch监听到screenWidth,但是当改变窗口大小时,并不会打印改变之后的值,即只监听了一次,不能持续监听,于是在mounted中调用window.onresize方法,然后就可以持续监听了
本文介绍了一种在Vue.js中实时监测屏幕宽度变化的方法。通过组合使用data属性、watch监听及window.onresize事件,实现对窗口尺寸变化的响应式更新。
884

被折叠的 条评论
为什么被折叠?



