vue对象监听如何实现
Vue 对象监听实现方法
Vue 提供了多种方式监听对象的变化,以下是常见的实现方法:
使用 watch 选项
在 Vue 实例中通过 watch 选项监听对象变化:
new Vue({
data() {
return {
user: {
name: 'John',
age: 30
}
}
},
watch: {
'user.name'(newVal, oldVal) {
console.log(`Name changed from ${oldVal} to ${newVal}`)
},
user: {
handler(newVal, oldVal) {
console.log('User object changed', newVal)
},
deep: true // 深度监听
}
}
})
使用 $watch API
在组件内动态添加监听器:
export default {
mounted() {
this.$watch(
'user.name',
(newVal, oldVal) => {
console.log(`Name changed from ${oldVal} to ${newVal}`)
}
)
this.$watch(
() => this.user,
(newVal, oldVal) => {
console.log('User object changed', newVal)
},
{ deep: true }
)
}
}
使用计算属性
通过计算属性间接监听对象属性:
export default {
data() {
return {
user: {
name: 'John',
age: 30
}
}
},
computed: {
userName() {
return this.user.name
}
},
watch: {
userName(newVal, oldVal) {
console.log(`Name changed from ${oldVal} to ${newVal}`)
}
}
}
使用 Vue.set 或 this.$set
对于新增属性,需要使用特殊方法使其响应式:
this.$set(this.user, 'newProperty', 'value')
// 等同于
Vue.set(this.user, 'newProperty', 'value')
使用 Vue.observable
创建可观察对象(Vue 2.6+):
const state = Vue.observable({
count: 0
})
// 在组件中使用
export default {
computed: {
count() {
return state.count
}
}
}
注意事项
- 深度监听 (
deep: true) 会遍历对象所有属性,可能影响性能 - 数组变化需要特殊处理,推荐使用数组变更方法 (push/pop/shift/unshift/splice/sort/reverse)
- 对象属性添加/删除需要使用
Vue.set/Vue.delete保证响应式 - Vue 3 中使用
reactive和ref替代 Vue 2 的响应式系统







