vue监听实现
Vue 监听实现方法
在 Vue 中可以通过多种方式实现监听数据变化或事件触发,以下是常见的几种方法:
使用 watch 选项
watch 是 Vue 提供的核心功能之一,用于观察和响应 Vue 实例上的数据变动。
export default {
data() {
return {
message: 'Hello'
}
},
watch: {
message(newVal, oldVal) {
console.log('Message changed from', oldVal, 'to', newVal)
}
}
}
使用 $watch API
可以通过 this.$watch 在组件实例中动态添加监听器。
export default {
created() {
this.$watch('message', (newVal, oldVal) => {
console.log('Message changed from', oldVal, 'to', newVal)
})
}
}
使用计算属性
计算属性 (computed) 会根据依赖自动更新,适合需要基于其他数据计算值的场景。

export default {
data() {
return {
firstName: 'John',
lastName: 'Doe'
}
},
computed: {
fullName() {
return this.firstName + ' ' + this.lastName
}
}
}
监听 DOM 事件
可以通过 v-on 指令或 @ 简写监听 DOM 事件。
<template>
<button @click="handleClick">Click me</button>
</template>
<script>
export default {
methods: {
handleClick() {
console.log('Button clicked')
}
}
}
</script>
使用事件总线
对于非父子组件间的通信,可以创建事件总线。
// event-bus.js
import Vue from 'vue'
export const EventBus = new Vue()
// Component A
EventBus.$emit('event-name', payload)
// Component B
EventBus.$on('event-name', payload => {
console.log('Event received', payload)
})
使用 Vuex
在大型应用中,Vuex 提供集中式状态管理,可以监听 store 的变化。

// store.js
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
}
})
// Component
export default {
computed: {
count() {
return this.$store.state.count
}
},
watch: {
count(newVal) {
console.log('Count changed to', newVal)
}
}
}
监听路由变化
可以使用 watch 监听 $route 对象的变化。
export default {
watch: {
'$route'(to, from) {
console.log('Route changed from', from.path, 'to', to.path)
}
}
}
深度监听对象
对于对象或数组,需要深度监听才能捕获嵌套属性的变化。
export default {
data() {
return {
user: {
name: 'Alice',
age: 25
}
}
},
watch: {
user: {
handler(newVal) {
console.log('User changed', newVal)
},
deep: true
}
}
}
立即触发监听
有时需要在监听时立即执行回调函数。
export default {
watch: {
message: {
handler(newVal) {
console.log('Message is', newVal)
},
immediate: true
}
}
}
每种监听方法适用于不同的场景,选择合适的方法可以提高代码的可维护性和性能。






