vue实现监听
监听数据变化
在Vue中,可以通过watch选项或$watch方法监听数据的变化。watch适用于组件选项内声明式监听,$watch适用于动态监听。
// 选项式API
export default {
data() {
return {
message: 'Hello'
}
},
watch: {
message(newVal, oldVal) {
console.log('Message changed:', oldVal, '->', newVal)
}
}
}
// 组合式API
import { ref, watch } from 'vue'
const message = ref('Hello')
watch(message, (newVal, oldVal) => {
console.log('Message changed:', oldVal, '->', newVal)
})
监听对象属性
监听对象属性需要使用深度监听或指定具体路径。Vue默认不深度监听对象内部变化。
watch: {
'user.name': {
handler(newVal, oldVal) {
console.log('Name changed:', oldVal, '->', newVal)
},
immediate: true // 立即触发
},
user: {
handler(newVal) {
console.log('User object changed:', newVal)
},
deep: true // 深度监听
}
}
监听多个数据源
使用数组可以同时监听多个响应式数据源,回调参数也会是数组形式。

watch([firstName, lastName], ([newFirst, newLast], [oldFirst, oldLast]) => {
console.log('Names changed:', oldFirst, oldLast, '->', newFirst, newLast)
})
监听路由变化
通过watch可以监听$route对象的变化,常用于路由参数变化时的数据更新。
watch: {
'$route'(to, from) {
if (to.params.id !== from.params.id) {
this.fetchData(to.params.id)
}
}
}
计算属性监听
计算属性会自动追踪依赖,当依赖变化时会重新计算。适合派生状态的监听。

computed: {
fullName() {
return this.firstName + ' ' + this.lastName
}
}
事件监听
组件可以通过$on方法监听自定义事件,或使用v-on指令监听DOM事件。
<template>
<button @click="handleClick">Click</button>
<child-component @custom-event="handleCustomEvent" />
</template>
<script>
methods: {
handleClick() {
console.log('Button clicked')
},
handleCustomEvent(payload) {
console.log('Custom event received:', payload)
}
}
</script>
生命周期钩子监听
Vue提供了一系列生命周期钩子,可以监听组件不同阶段的状态变化。
export default {
created() {
console.log('Component created')
},
mounted() {
console.log('Component mounted')
},
updated() {
console.log('Component updated')
},
destroyed() {
console.log('Component destroyed')
}
}
第三方库集成
对于复杂状态管理,可以集成Vuex或Pinia,它们提供了更强大的状态监听能力。
// 使用Pinia
import { useStore } from '@/stores/counter'
import { storeToRefs } from 'pinia'
const store = useStore()
const { count } = storeToRefs(store)
watch(count, (newVal) => {
console.log('Count changed:', newVal)
})






