语法:
watch(侦听源,回调函数,选项)
1. 参数:
1.1. 选项:
选项是可省的, 是一个对象
特殊意义的键值对:
flush: 'sync'- 功能: 多个侦听源同时改变的时候, 侦听器会触发多次
- 默认只触发一次
- 不过不推荐使用, 更推荐使用nextTick
- 功能: 多个侦听源同时改变的时候, 侦听器会触发多次
flush: 'post'- 功能: 在变量更新之后, 再调用回调函数
- 默认在变量更新之前调用
- 功能: 在变量更新之后, 再调用回调函数
deep: true- 功能: 能够监听对象监听源的深层属性的变化
- 默认只能监听对象第一层属性值的更改
- 功能: 能够监听对象监听源的深层属性的变化
特殊意义的方法:
实例:
1. 监听对象的深层属性:
const state = reactive({
id: 1,
attributes: {
name: '',
}
})
watch(
() => state,
(state, prevState) => {
console.log('not deep', state.attributes.name, prevState.attributes.name)
}
)
watch(
() => state,
(state, prevState) => {
console.log('deep', state.attributes.name, prevState.attributes.name)
},
{ deep: true }
)
state.attributes.name = 'Alex' // 日志: "deep" "Alex" "Alex"2. 说明:
- base::reactive()