preface

Today, I encountered a problem during the development, that is, after the value was passed to the child component, the value was changed in the child component, which led to a warning from Vue. After looking at the document carefully, Vue follows a single data stream: 1. That is, only the parent component is allowed to pass parameters to the child component, and the child component is not allowed to pass parameters to the parent. 2. The child component changes when the parent component changes its parameter value, but the parent component does not change when the child component changes its parameter value, and the child component changes its parameter value.

content

Without further ado, let’s take an exampleWe changed this by registering a global component Test, passing two values to it, binding a method changeValue to the child component, and passing the parent component gender to it. Look at the Chrome console and see this information

The solution

You can declare a variable on data or computedYou can see that the console does not report an error when we change the genderCopy value, but there is one detail:In this case, the variable declared using data is passed down by the value and is not a reference type, so here our parent component changes this parameter, and the child component will not synchronize the change. If we want to synchronize the change at this time, we can use watch

Some points to note

When the value passed by props is a reference type, such as a set of props or an object, and we change the value passed by the child component, we also change the parent component’s value, but we don’t get the console warning that the basic type does

Because in js, objects and arrays are reference types, point to the same memory space, so when we through the v – bind binding parameter is an array or object, and then passed, then they will affect the parent component of change in the child components, (this has nothing to do with the vue component, determined by the characteristics of js, if you want to avoid this situation, When the child component receives the reference type parameter, it can handle it, such as using the JSON method or using the object.assign () method.