3

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?

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Defining comments as reactive does not make it reactive in the Comment component. That's what is being asked. The only way to make it reactive is define comments as a ref. Not sure if there is a bug in vue3 or if there's something else we're suppose to do to make it truly reactive in another component.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.