skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

    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.


  2. At first, I’m not very clear what you want to ask, Your code in playground has show me that you may want to use the writable-computed,

    The const name = ref(props.data.Name) will only create a new ref with props.data.Name as default value, so it will not change when props update.

    Then about your question

    What is the correct way to really seal a component?

    I think that change the prop’s property is not a good way however vue allow you do this. The good way to do is update the value with event. And the v-model is also a prop and a event v-model:visible="xxx" => :visible="xxx" @update:visible="xxx"

    You may can create a ref in your component and watch your props, when the ref change, make a event to ask parent component and when the prop change update your ref. Also it have alreay been implemented in useVModel in @vue/use, I suggest that you can try to use it and read their codes.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search