vue.jsvuejs3

Modifying a prop in a child component?


I have a parent component that passes in an error as a prop.

Inside my child component I want to modify the error prop. This is not allowed.

So, I can create a local copy...

const error = props.error;

But when the parent updates error the child does not receive the update in the local var.

How to address this.

Note, I wish to create a copy in the child component so I can modify it in the child component.


Solution

  • I recommend using a computed if you want to have a copy of the prop from the parent. A regular JS variable will not be reactive, unfortunately.

    This question is still relevant for Vue3 I think. There is no new hacky way to do it either because it is seen as an anti-pattern anyway.

    Another cleaner approach would be to use a watcher or a method to mutate a local ref state in the child, that way you do not touch the prop, just have a local dependency in the child based on the prop passed from the parent.


    PS: more context regarding the why.

    TLDR is mostly that you should keep it straightforward between the parent and child so that it's easy to debug.
    It is meanwhile marked as Use with Caution in the style guide, hence you could just ignore that rule and live your life on the edge if you are fine with doing it in a non-Vue way.