TestPage.vue:
<template>
<div>
<TestChild :dog = "this.parentDog" />
<div v-on:click="this.changeName" id="change-button">
Change Parent Dog name
</div>
</div>
</template>
<script>
import TestChild from "@/test/TestChild";
export default {
components: {TestChild },
methods: {
changeName() {
this.parentDog.name = "Changed First Name";
alert("Changed!");
}
},
data() {
return {
parentDog: {
name: "First Dog"
}
};
},
};
</script>
<style>
#change-button {
margin: 2em;
padding: 1em;
background-color: green;
}
</style>
TestChild.vue:
<template>
<div>{{this.betterDog.name}}</div>
</template>
<script>
import {ref} from 'vue';
export default {
name: "TestChild",
props: {
dog: Object
},
data() {
return {
betterDog: Object
};
},
created() {
this.betterDog = {};
this.betterDog.name = ref(this.dog.name);
}
};
</script>
点击绿色按钮之前的输出:
TestPage
的数据:
TestChild
的数据:
parentDog
中的TestPage
和betterDog
中的TestChild
的名称是相同的。
点击绿色按钮后,页面输出没有变化。数据变化如下:
TestPage
的数据:
TestChild
的数据:
因此,单击按钮后,
dog
组件中的 TestChild
属性会反映更改,但 betterDog
数据却不会,尽管使用了 ref
。
如何使
betterDog.name
也具有反应性?在 watch
道具上不使用 dog
。
Composition API 应该取代 options API,它们可以一起使用,但这会导致难以理解和未记录的情况。这里使用
ref
是不合理的,也没有用。 data
状态已经是响应式的,在 Vue 3 中不需要任何增强。当在响应式对象中使用时,引用会被解开,这里就是这种情况。
需要计算者或观察者来将反应性属性与其他属性同步。除非
betterDog
可以在子组件的生命周期内独立于 parentDog
更改属性,否则它不需要成为组件状态的一部分,也不需要观察者:
computed: {
betterDogName() {
return this.dog.name
}
betterDog: Object
是一个错误,data
应该返回初始值,而Object
是一个函数。然而,这并不影响它在这里的工作方式。