目录
一、Watch() 函数概述
在Vue中,可以使用watch函数来监听数据的变化,并在变化时执行相应的操作。
watch函数接受两个参数:
1. 第一个参数是要监听的数据或属性的选择器,可以是一个对象、数组、函数等;
2. 第二个参数是一个回调函数,当数据发生变化时,回调函数会被执行。
下面是一个简单的例子,演示如何使用watch函数来监听一个数组的长度变化:
// 定义一个数组
let arr = [1, 2, 3, 4, 5];
// 定义一个watch函数,监听数组长度的变化
watch: {
length: function(newLength, oldLength) {
console.log('数组长度发生变化:', newLength, oldLength);
// 在这里处理数组长度变化的逻辑
}
}
在上面的例子中,我们定义了一个数组arr,并使用watch函数来监听它的长度变化。当数组长度发生变化时,会在控制台中输出一条信息,并且我们可以在回调函数中处理数组长度变化的逻辑。
除了数组长度之外,watch函数还可以监听其他数据的变化,例如数据的属性、计算属性等。具体用法可以参考Vue官方文档。
二、Vue中追加屏幕宽度监听
1. data()中定义一个屏幕宽度全局变量 screenWidth
<template>
...
</template>
<script>
export default {
...
data() {
return {
// 屏幕宽度
screenWidth: document.body.clientWidth,
}
}
}
</script>
2. 使用watch()函数监听窗口大小
<template>
<div
v-bind:class="{
'css-div-hd': screenWidth < 1400,
'css-div-fhd': screenWidth > 1400,
}"
>
</div>
</template>
<script>
export default {
...
data() {
return {
// 屏幕宽度
screenWidth: document.body.clientWidth,
}
},
mounted: async function () {
window.onresize = () => {
return (() => {
this.screenWidth = document.body.clientWidth;
});
};
},
watch: {
screenWidth(val) {
this.screenWidth = val;
this.screenWidthChanged();
},
},
methods: {
screenWidthChanged(){
// 屏幕宽度发生变化时的逻辑处理
// TODO
},
},
}
</script>
<style scoped>
.css-div-hd {
width: 1400px;
}
.css-div-fhd {
width: 1920px;
}
</style>