英文:
why the oldvalue is same to the new value in the vue3 Watch,
问题
<script setup lang="ts">
import { ref, reactive, watch, watchEffect } from 'vue'
interface address {
nation: string
}
interface basketballPlayer {
name: string
age: number
address: address
}
let str = ref<string>('jth')
let basketballPlayer = ref<basketballPlayer>({
name: 'jokic',
age: 28,
address: {
nation: 'Seriba',
},
})
const handleClick = (): void => {
str.value = 'Eric'
basketballPlayer.value.address.nation = 'americal'
}
watch(
[str, basketballPlayer],
(newVal, oldVal) => {
console.log(newVal, oldVal)
},
{
deep: true,
}
)
</script>
<template>
<div>
watch
<a-button type="primary" @click="handleClick">更改</a-button>
</div>
</template>
<style scoped></style>
查看图片描述 我定义了一个对象,并且它有一个深层结构。当我点击按钮并修改了地址的国家时,控制台栏会显示两个对象具有相同的数据,旧值与新值相同,为什么?
英文:
<script setup lang="ts">
import { ref, reactive, watch, watchEffect } from 'vue'
interface address {
nation: string
}
interface basketballPlayer {
name: string
age: number
address: address
}
let str = ref<string>('jth')
let basketballPlayer = ref<basketballPlayer>({
name: 'jokic',
age: 28,
address: {
nation: 'Seriba',
},
})
const handleClick = (): void => {
str.value = 'Eric'
basketballPlayer.value.address.nation = 'americal'
}
watch(
[str, basketballPlayer],
(newVal, oldVal) => {
console.log(newVal, oldVal)
},
{
// immediate: true,
deep: true,
}
)
</script>
<template>
<div>
watch
<a-button type="primary" @click="handleClick">更改</a-button>
</div>
</template>
<style scoped></style>
enter image description here
I define a object,and it has a deep structure,when i clike the button,and modified the address's nation,the console bar shows that,the two object has the same data,old value is same to new value,why
答案1
得分: 1
在文档中提到了:
> 注意,在深度模式下,如果回调由深层次的变化触发,新值和旧值将是相同的对象。
如果您想看到差异,您必须使用一个getter
watch(
() => basketballPlayer.value.address.nation,
(oldVal, newVal) => {
console.log('oldVal', oldVal);
console.log('newVal', newVal);
}
);
英文:
In the doc, they have mentioned it:
> Note in deep mode, the new value and the old will be the same object
> if the callback was triggered by a deep mutation.
If you want to see the difference, you have to use a getter
watch(
() => basketballPlayer.value.address.nation,
(oldVal, newVal) => {
console.log('oldVal', oldVal);
console.log('newVal', newVal);
}
);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论