1.

What is the data flow heeded by props, and what are the possible solutions for mutation cases?

Answer»

All props follow a ONE-way-down binding between the child's property and the PARENT one. i.e., when the parent property is updated, that latest prop value will be passed down to the child, but not the other way(child to parent, which is carried out by emitting events rather than using props).  

The child component should not mutate the prop defined in the parent; otherwise, it throws a warning in the console. The possible mutation cases can be solved in the ways illustrated below.  

The possible mutation cases are: 

  1. When you try to use parent prop as the initial value for child property: 

The solution for this mutation case is defining a local property in the child component and assigning the parent value as the initial value. The following code snippet clarifies the solution. 

props: ['defaultUser'], 
  • defaultUser prop is the one defined in the parent component whose value is GOING to be assigned to the child's local property as an initial value. 

data: function () {    return {     username: this.defaultUser    }  }
  • Username is the local property of the child whose initial value is the parent's prop (defaultUser) 

  1. When you try to transform the parent prop: 

The solution for this mutation case is defining a computed property using the prop's value. Computed properties are ANOTHER powerful feature from Vue that allows us to transform or perform calculations on our data and easily REUSE the result as an up-to-date variable in our template. 

Below is the illustration of computed properties to mutate the parent's prop  

 props: ['environment'],  computed: {   localEnvironment: function () {     return this.environment.trim().toUpperCase()    }  }


Discussion

No Comment Found

Related InterviewSolutions