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>

点击绿色按钮之前的输出:

enter image description here

The data for the TestPage: enter image description here The data for the TestChild: enter image description here

TestPageparentDog的名字和TestChildbetterDog的名字相同.

单击绿色按钮后,页面输出不会更改.数据变化如下:

The data for the TestPage: enter image description here The data for the TestChild: enter image description here

因此,单击按钮后,TestChild组件中的dogprops 反映了这一变化,但尽管使用了refbetterDog数据却没有反映这一变化.

如何让betterDog.name也成为react 型?无需在dog上使用watch.

推荐答案

组合API应该取代选项API,可以将它们一起使用,但这会导致难以理解和无记录的情况.这里使用ref是不合理的,也没有用.data状态已经是react 式的,不需要Vue 3中的任何增强.当在react 性对象内部使用时,为Refs are unwrapped,这里就是这种情况.

需要计算者或观察者才能将react 属性与其他属性同步.除非betterDog可以在子组件的生命周期内独立于parentDog更改属性,否则它不需要成为组件状态的一部分,也不需要观察者:

computed: {
  betterDogName() {
   return this.dog.name
 }

betterDog: Object是一个错误,data应该返回初始值,而Object是一个函数.然而,这并不影响它在这里的工作方式.

Javascript相关问答推荐

如何使用React渲染器放置根dis?

有Angular 的material .未应用收件箱中的价值变化

fs. writeFile()vs fs.writeFile()vs fs.appendFile()

我开始使用/url?q=使用Cheerio

了解Node.js中的EventEums和浏览器中的addEventEums之间的关系

如何修复(或忽略)HTML模板中的TypeScript错误?'

将现场录音发送到后端

实现JS代码更改CSS元素

如何使用子字符串在数组中搜索重复项

如何在使用rhandsontable生成表时扩展数字输入验证?

确保函数签名中的类型安全:匹配值

400 bad request error posting through node-fetch

为什么客户端没有收到来自服务器的响应消息?

Jest toHaveBeenNthCalledWith返回当前设置的变量值,而不是调用时的值

postman 预请求中的hmac/sha256内标识-从js示例转换

FireBase FiRestore安全规则-嵌套对象的MapDiff

JavaScript将字符串数字转换为整数

将字符串解释为数字;将其重新编码为另一个基数

找不到处于状态的联系人

由于http.get,*ngIf的延迟很大