【问题标题】:Are parameters ref or reactive in Vue 3 composition API?Vue 3组合API中的参数是参考还是反应?
【发布时间】:2021-10-25 18:54:53
【问题描述】:

在组合 API 中,反应性使用 ref() 和 reactive() 函数为数据创建代理。据我了解,主要区别在于ref 创建的是浅拷贝,而reactive 创建的是对象的深层拷贝。

我将一个对象作为参数传递给一个组件,但我遇到了反应性问题。具体来说,对象的字段在更新时不会触发 UI 中的任何更改。这让我相信参数是作为 refs 而不是响应式对象传递的。

有没有办法在对象的内容发生变化时更新视图?

【问题讨论】:

    标签: vuejs3 vue-composition-api


    【解决方案1】:

    其实 ref 不会创建浅拷贝,一旦你将一个 obj 传递给一个 ref,它就会调用 createReactiveObject 方法来生成一个响应式对象。关于浅参考,您可以使用 shallowref 方法,https://v3.vuejs.org/api/refs-api.html#shallowref

    由于您没有提供任何代码,这里仅举一个简单的例子供您参考:

    将 cmets 定义为响应式对象,child 不需要为 props 引用:

    父组件:

    <template>
      <Comment v-for="comment in comments" :comment="comment" :key="comment.id"></Comment>
      <button @click="addCmt">addCmt</button>
    </template>
    
    <script>
    import Comment from "./components/Comment";
    import {reactive} from "vue";
    export default {
      name: "Params",
      setup() {
        const comments = reactive([{id: 1, name: 'a'}, {id: 6, name: 'c'}]);
        function addCmt() {
          comments.unshift({id: comments.length + 10, name: 'k'});
        }
        return {
          comments,
          addCmt
        }
      },
      components: {Comment}
    }
    </script>
    

    评论组件:

    <template>
      <div>comments {{ comment.id }}</div>
    </template>
    
    <script>
    export default {
      name: "Comment",
      props: ['comment'],
      setup(props, ctx) {
        const comment = props.comment;
        return {comment};
      }
    }
    </script>
    

    【讨论】:

      猜你喜欢
      • 2021-02-11
      • 2018-01-01
      • 1970-01-01
      • 2011-10-27
      • 2011-04-15
      • 1970-01-01
      • 2020-08-01
      • 1970-01-01
      相关资源
      最近更新 更多