vue实现数据监听
Vue 数据监听实现方式
Vue 提供了多种方式实现数据监听,核心机制基于响应式系统。以下是常见方法:
使用 watch 选项
在组件选项中直接定义 watch 对象,监听特定数据变化:
export default {
data() {
return {
message: 'Hello'
}
},
watch: {
message(newVal, oldVal) {
console.log('Message changed:', newVal)
}
}
}
立即执行的 watch
添加 immediate: true 使监听器立即执行一次:
watch: {
message: {
handler(newVal) {
console.log('Initial load:', newVal)
},
immediate: true
}
}
深度监听对象
设置 deep: true 监听对象内部变化:
watch: {
user: {
handler(newVal) {
console.log('User data changed')
},
deep: true
}
}
计算属性 computed
派生状态监听,自动依赖追踪:
computed: {
reversedMessage() {
return this.message.split('').reverse().join('')
}
}
$watch API
编程式动态添加监听器:
created() {
this.$watch(
() => this.count,
(newVal) => {
console.log('Count changed to:', newVal)
}
)
}
数组变化监听
Vue 能检测以下数组方法触发的变更:
push()
pop()
shift()
unshift()
splice()
sort()
reverse()
响应式原理
Vue 3 使用 Proxy 实现响应式,Vue 2 使用 Object.defineProperty。手动使新属性响应式:
// Vue 2
this.$set(this.obj, 'newProp', value)
// Vue 3
import { reactive } from 'vue'
const state = reactive({ count: 0 })
选择合适的方式取决于具体场景:简单数据变化用 watch,派生数据用 computed,需要深度监听时配置 deep 选项。







