vue实现监听
监听数据变化
在Vue中,可以使用watch选项或$watch方法来监听数据的变化。watch适用于监听单个数据属性,而$watch适用于动态监听或组件销毁时自动取消监听。
// 使用watch选项
export default {
data() {
return {
message: 'Hello'
}
},
watch: {
message(newVal, oldVal) {
console.log(`Message changed from ${oldVal} to ${newVal}`)
}
}
}
// 使用$watch方法
export default {
data() {
return {
message: 'Hello'
}
},
created() {
this.$watch('message', (newVal, oldVal) => {
console.log(`Message changed from ${oldVal} to ${newVal}`)
})
}
}
深度监听对象
默认情况下,watch只监听对象的引用变化。如果需要监听对象内部属性的变化,可以使用deep选项。
export default {
data() {
return {
user: {
name: 'John',
age: 30
}
}
},
watch: {
user: {
handler(newVal, oldVal) {
console.log('User changed')
},
deep: true
}
}
}
立即触发监听
有时需要在组件创建时立即执行监听函数,可以使用immediate选项。
export default {
data() {
return {
count: 0
}
},
watch: {
count: {
handler(newVal, oldVal) {
console.log(`Count is ${newVal}`)
},
immediate: true
}
}
}
监听计算属性
计算属性本身是响应式的,可以直接在watch中监听。
export default {
data() {
return {
firstName: 'John',
lastName: 'Doe'
}
},
computed: {
fullName() {
return `${this.firstName} ${this.lastName}`
}
},
watch: {
fullName(newVal, oldVal) {
console.log(`Full name changed to ${newVal}`)
}
}
}
监听路由变化
在Vue Router中,可以使用watch监听$route对象的变化。
export default {
watch: {
'$route'(to, from) {
console.log(`Route changed from ${from.path} to ${to.path}`)
}
}
}
监听多个数据源
如果需要监听多个数据源,可以使用数组形式的watch键。
export default {
data() {
return {
x: 0,
y: 0
}
},
watch: {
['x', 'y']([newX, newY], [oldX, oldY]) {
console.log(`Position changed from (${oldX}, ${oldY}) to (${newX}, ${newY})`)
}
}
}
使用侦听器清理
在组件销毁时,手动创建的侦听器需要清理。使用$watch返回的函数可以取消侦听。
export default {
data() {
return {
timer: null
}
},
created() {
const unwatch = this.$watch('timer', (newVal) => {
console.log(`Timer updated: ${newVal}`)
})
// 在组件销毁时取消侦听
this.$once('hook:beforeDestroy', unwatch)
}
}
性能优化
对于频繁变化的数据,可以使用debounce或throttle来优化性能。
import { debounce } from 'lodash'
export default {
data() {
return {
searchQuery: ''
}
},
watch: {
searchQuery: debounce(function(newVal) {
console.log(`Searching for: ${newVal}`)
}, 500)
}
}






