vue prop unidirectional data flow

Prop is one-way binding: when a property of the parent component changes, it is propagated to the child component, but not the other way around. This is to prevent child components from inadvertently modifying the parent's state, preventing the application's data flow from becoming unintelligible.

Also, every time the parent component is updated, all props of the child component are updated to the latest value. This means you shouldn't change props inside child components. If you do, Vue will warn you in the console.

In two cases, it is easy to resist the temptation to modify the data in the prop:

  1. After Prop is passed in as the initial value, the child component wants to use it as local data;

  2. Prop is passed in as raw data and processed by child components into other data output.

In both cases, the correct response is:

  1. Define a local variable and initialize it with the value of prop:

props: ['initialCounter'],
data: function () {
  return { counter: this.initialCounter }
}

  2. Define a computed property, process the value of prop and return:

props: ['size'],
computed: {
  normalizedSize: function () {
    return this.size.trim().toLowerCase()
  }
}

The principle is: Note that in JavaScript, objects and arrays are reference types, pointing to the same memory space. If prop is an object or an array, changing it inside the child component will affect the state of the parent component .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324780970&siteId=291194637