watch基本格式
watch(监听的数据,作用函数,监听配置)
watch(data,
(newData, oldData) => {},
{ immediate: true, deep: true })
deep:true 开启深度监听
当data为reactive数据时必开启,不然不触发监听
------
immediate:true 页面渲染后立刻触发监听
最好所有watch都配置,不然会出现watch监听不触发问题
const data = ref('开始')
const stu = reactive({
name: '张三',
age: '12'
})
watch(data, (newName, oldName) => {
console.log("newName", newName);
}{ immediate:true });
watch(stu, (newName, oldName) => {
console.log("newName", newName);
},{ deep: true,immediate:true });
watch(() => stu.name,(newVal,oldVal)=>{
console.log(newVal,'新')
console.log(oldVal,'旧')
},{ deep: true,immediate:true })
props: {
index: {
type: Number,
default: 0
}
},
watch(() => props.index,(newVal,oldVal)=>{
console.log(newVal,'新')
console.log(oldVal,'旧')
},{ deep: true,immediate:true })