Search code examples
javascriptvue.jspointersvuejs3components

How to ensure changes in props do not bubble up?


I realized that my props passed to a component, and changed in the component, may bubble up. This is mentioned in the documentation.

When objects and arrays are passed as props, while the child component cannot mutate the prop binding, it will be able to mutate the object or array's nested properties.

I recreated a case like that at the Vue Playground. As you can see, pushing 'hello' in the Comp.vue component changes the value of the prop in the parent App.vue.

What the documentation does not suggest is a way to break this binding. I thought that creating unitary refs in the component (from the props object) would break that link but as the code shows this is not the case.

What is the correct way to really seal a component?

Note: I need the variables in the component to be reactive in order to use them in the component template (and have them modified on the fly) This is mentioned in another question and its answers but there is no solution for objects with nested Arrays like in my case.


Solution

  • I managed to break the reactivity link by spreading the props into the component's reactive variable. For the code mentioned in the Vue Playground, this means having

    const books = ref([...props.data.Books])
    // was: const books = ref(props.data.Books)
    

    From there on, books is reactive within the component and inherits of the props values, but its changes are not propagated back to the parent.