Component combination

The original intention of component design is to be used together, and the most common one is to form a parent-child component relationship: component A uses component B in its template. They must communicate with each other: the parent component may send data to the child component, and the child component may inform the parent component of what is happening inside it. However, it is also important to decouple parent and child components as much as possible through a well-defined interface. This ensures that the code of each component can be written and understood in a relatively isolated environment, thereby improving its maintainability and reusability.

In Vue, the relationship between parent and child components can be summarized as  props are passed down and events are passed up . The parent component  sends data to the child component through props , and the child component sends messages to the parent component through events

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 state of the parent component, 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 that handles the value of the prop and returns:

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

Guess you like

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