Vue的watch
属性提供了一种观察和响应Vue实例上数据变化的能力。以下是一些常见的使用场景和详细案例:
1. 监听数据变化并执行异步操作
<template>
<input v-model="username">
</template>
<script>
export default {
data() {
return {
username: ''
};
},
watch: {
username(newVal, oldVal) {
if (newVal !== oldVal) {
this.fetchUserData();
}
}
},
methods: {
fetchUserData() {
// 假设根据用户名获取用户数据的异步操作
console.log(`Fetching data for user: ${this.username}`);
}
}
};
</script>
2. 监听路由变化
<template>
<div>{{ routePath }}</div>
</template>
<script>
export default {
data() {
return {
routePath: ''
};
},
watch: {
'$route'(to, from) {
this.routePath = to.path;
}
}
};
</script>
3. 监听深层数据变化
<template>
<div>{{ user.name }}</div>
</template>
<script>
export default {
data() {
return {
user: { name: 'John', age: 30 }
};
},
watch: {
'user.name'(newVal, oldVal) {
console.log(`Name changed from ${oldVal} to ${newVal}`);
}
}
};
</script>
4. 监听对象属性并执行复杂逻辑
<template>
<div>{{ user.age }}</div>
</template>
<script>
export default {
data() {
return {
user: { name: 'John', age: 30 }
};
},
watch: {
'user.age': {
handler(newVal, oldVal) {
if (newVal > 18) {
console.log('User is an adult');
} else {
console.log('User is a minor');
}
},
deep: true
}
}
};
</script>
5. 立即执行并监听数据变化
<template>
<div>{{ computedValue }}</div>
</template>
<script>
export default {
data() {
return {
multiplier: 2
};
},
computed: {
computedValue() {
return this.multiplier * 10;
}
},
watch: {
computedValue: {
immediate: true,
handler(newVal, oldVal) {
console.log(`Computed value changed from ${oldVal} to ${newVal}`);
}
}
}
};
</script>
6. 监听数据并执行防抖操作
<template>
<input v-model="searchText">
</template>
<script>
export default {
data() {
return {
searchText: ''
};
},
watch: {
searchText: _.debounce(function(newVal, oldVal) {
console.log(`Search text changed to: ${newVal}`);
}, 500)
}
};
</script>
在这个例子中,我们使用了lodash
库的debounce
函数来限制搜索文本变化的监听频率。
注意事项
- 使用
watch
时,可以指定选项,如immediate
、deep
、handler
等,以满足不同的监听需求。 - 对于复杂的监听逻辑,考虑使用方法(methods)或计算属性(computed)。
- 确保在组件销毁时清理
watch
,以避免内存泄漏,尤其是使用了异步操作或定时器的情况。
通过上述案例,你可以看到Vue的watch
属性在不同场景下的应用,它们可以帮助你以声明式的方式构建响应式的数据观察逻辑。