“This is the 7th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

1. Background

In VUE, the most common ways for parent and child components to communicate are props and $emit, but the parent component passes data to the child component, but cannot modify the value of the properties in the props

2. A detailed explanation of the usage and principle of the. Sync modifier in vue, to solve the problem of dynamic modification of values transmitted between components

The parent component passes the props to the child component. How can I avoid an error when the child component changes the props property value

  • In vue we often use v-bind(abbreviated 🙂 to pass arguments to child components. Or we might pass a function to a child component, which changes the state of the parent component by calling the function.
// The parent passes a function to the child <MyFooter :age="age" @setage ="(res)=> age= res"></MyFooter> the child calls this function to modify the state of the parent. mounted () { console.log(this.$emit('setAge',1234567)); }Copy the code
  • In this case, the child component triggers the parent component’s change function so that the parent component changes its age to 1234567. This is a very common case, and the cutting method is a bit more complicated. Which brings us to today’s hero,.sync
// The parent passes age to the child and uses the.sync modifier. <MyFooter :age. Sync ="age"></MyFooter> // Console. log(this.$emit('update:age',1234567)); // MyFooter :age ="age"></MyFooter> // Console. log(this. }Copy the code

Notice here that our event name has been changed to Update :age. Update: is fixed which is the part of the name that vue has agreed on for us. Age is the name of the state that we want to change, which we manually configure to correspond to the name of the state that was passed in

That’s it. Doesn’t it feel a lot easier.

Note: We must prefix the event execution name with update: to properly fire the event

3. Conclusion:

When a parent component passes a value, the parameters, arrays, and objects passed by the parent component can be directly modified by the child component, and the values passed to the parent component can also be modified.

If the value passed is a string, modifying it directly will cause an error.

It is not recommended that a child component modify a parameter in the parent component directly. Otherwise, the parameter is referenced by multiple child components and the data is abnormal