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>
点击绿色按钮之前的输出:
The data for the TestPage
:
The data for the TestChild
:
TestPage
中parentDog
的名字和TestChild
中betterDog
的名字相同.
单击绿色按钮后,页面输出不会更改.数据变化如下:
The data for the TestPage
:
The data for the TestChild
:
因此,单击按钮后,TestChild
组件中的dog
props 反映了这一变化,但尽管使用了ref
,betterDog
数据却没有反映这一变化.
如何让betterDog.name
也成为react 型?无需在dog
上使用watch
.