vue怎么实现数据监听
Vue 数据监听实现方式
Vue 提供了多种方式监听数据变化,以下是常用的方法:
使用 watch 选项
在 Vue 组件中可以通过 watch 选项监听特定数据的变化:
export default {
data() {
return {
message: 'Hello'
}
},
watch: {
message(newVal, oldVal) {
console.log('Message changed from', oldVal, 'to', newVal)
}
}
}
使用 $watch 方法
可以在组件实例上直接调用 $watch 方法进行监听:

export default {
created() {
this.$watch('message', (newVal, oldVal) => {
console.log('Message changed from', oldVal, 'to', newVal)
})
}
}
深度监听对象
对于对象或数组,需要设置 deep: true 进行深度监听:
watch: {
user: {
handler(newVal, oldVal) {
console.log('User object changed')
},
deep: true
}
}
立即触发监听
设置 immediate: true 可以在监听开始时立即执行回调:

watch: {
message: {
handler(newVal, oldVal) {
console.log('Message is now', newVal)
},
immediate: true
}
}
计算属性监听
对于依赖多个值的变化,可以使用计算属性:
computed: {
fullName() {
return this.firstName + ' ' + this.lastName
}
}
使用 Vue.set 或 this.$set
对于动态添加的响应式属性,需要使用 Vue.set 方法:
this.$set(this.user, 'age', 25)
监听路由变化
可以通过 watch 监听 $route 对象的变化:
watch: {
'$route'(to, from) {
console.log('Route changed from', from.path, 'to', to.path)
}
}
这些方法覆盖了 Vue 中数据监听的主要场景,可以根据具体需求选择合适的方式。






