Tibi
Tibi

Reputation: 499

Are parameters ref or reactive in Vue 3 composition API?

In the composition API reactivity uses the ref() and reactive() functions to create proxies for data. As far as I understand, the main difference is that ref creates a shallow copy while reactive creates a deep copy of the objects.

I am passing an object as a parameter to a component and I am having issues with reactivity. Specifically, fields of the object, while updating, do not trigger any changes in the UI. That leads me to believe that parameters are passed as refs rather than reactive objects.

Is there a way to have the view update when the content of the object changes?

Upvotes: 3

Views: 2020

Answers (1)

huan feng
huan feng

Reputation: 8623

Actually ref does not creates a shallow copy, once you pass an obj to a ref, it will call the createReactiveObject method to generate a reactive object. Regarding shallow ref, you can use the shallowref method, https://v3.vuejs.org/api/refs-api.html#shallowref

Since you have not provide any code, here just give you a simple example for your reference:

Define comments as a reactive object, child no need to ref for the props:

Parent component:

<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>

Comment component:

<template>
  <div>comments {{ comment.id }}</div>
</template>

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

Upvotes: 1

Related Questions