watch的侦听数据源类型
watch的第一个参数为侦听数据源,有4种"数据源":
ref(包括计算属性)
reactive(响应式对象)
getter函数
多个数据源组成的数组。
//ref
const x=ref(0)//单个ref
watch(x,(newX)=>{console.log(`x is ${newX}`)
})
//getter函数
const x = ref(0)
watch(
()=> x.value,
(newX)=>{console.log(`x is ${newX}`)}
)//getter函数const obj = reactive({count:0})
watch(
()=> obj.count,
(count)=>{console.log(`count is ${count}`)}
)
//reactive 隐式创建一个深层侦听器const obj = reactive({count:0});
watch(obj,
(newV,olbV)=>{// 在嵌套的属性变更时触发// 注意:`newV` 此处和 `oldV` 是相等的// 因为它们是同一个对象!},
)//或者
watch(
()=>obj.count,
()=>{// 仅当 obj.count被替换时触发}
)
// 多个来源组成的数组
const x=ref(0)
const y=ref(0)watch([x, () => y.value], ([newX, newY]) => {console.log(`x is ${newX} and y is ${newY}`)
})
watch属性:
{ deep: true } //强制转成深层侦听器,
深度侦听需要遍历被侦听对象中的所有嵌套的属性,当用于大型数据结构时,开销很大。因此请只在必要时才使用它,并且要留意性能。
{ immediate: true } //强制侦听器回调立即执行
{ once: true } // 3.4+,回调只在源变化时触发一次