Vue中watch监听属性新旧值相同问题解决方案
问题:Vue中watch监听属性新旧值相同。
<script setup> import {ref,watch} from 'vue' const person = ref({ name:'张三', age:100 }) const chanegPerson = () => { person.value.name = '李四' person.value.age++ } watch(person,(newValue,oldValue)=>{ console.log(newValue,oldValue); },{deep:true}) </script> <template> <div>{{name}}</div> <button @click="changeName">改名</button> <div>{{ num }}</div> <button @click="changeNum">改数</button> <!-- <button @click="count++">+1</button> --> <div>{{ person }}</div> <button @click="chanegPerson">改名</button> </template>
输出:

原因:监听复杂数据类型,当复杂数据类型被改变之后,newval的值改变,由于newval和oldval都指向同一个对象,导致oldval也会随之改变,则没有了old和new之分.
解决方法:在初始化的时候,深克隆一个旧值.。JSON.parse(JSON.stringify(oldvalue))
watch(()=> JSON.parse(JSON.stringify(person)),(newValue,oldValue)=>{ console.log(newValue,oldValue); },{deep:true})
输出:

浙公网安备 33010602011771号