<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方法,然后就可以持续监听了