application and provide inject contrast and props

Before I wrote several element ui source resolution, which refers to provide / inject, was just passing rush, he did not do in-depth research, until it was time to develop, implement Sun components change the value of the parent component to think of it, the original to attribute such a large and fairly easy to use, so there be a summary of the way to be a simple DEMO.

PS:

Below mentioned parent components, subassemblies, assemblies Sun just to illustrate three levels, to facilitate understanding of it

 

Scenario is as follows:

1, three components: a parent components, sub-assemblies, Sun components, refer to the child the parent, child references Sun

2, there is a parent component attributes: showDia. Subassemblies, assemblies Sun may change the value of this property, in order to achieve a parent component in a pop show hidden

 

The first implementation: the use of props

Since the props can only be achieved to pass parameters to achieve sub-components can not pass parameters directly to the Sun components, so each nesting level on the worse the deeper the need to pass parameters manually, nesting level experience, a bit like an asynchronous request nesting, simply nightmarish existence

// parent component subassembly references, values need to explicitly pass 
<SONC: fromParentVal = "showDia"> </ SONC> 

// referenced Sun subassembly components, need to explicitly pass values 
<grandSonC: fromGrandSonVal = "showDia" > </ grandSonC> 

// SUN components you want to modify the value of parent component showDia of 
this. $ parent. $ parent.showDia = ! this. $ parent. $ parent.showDia

  

When the need to modify the parent component value components in the Sun, there are several layers of nesting you need to write a few $ parent, it did not do so level

 

The second realization: provide / inject

As long as the parent components provide, Sun and subassembly components can be injected with inject, look at the code

// parent components provided this object, the injection assembly for descendants 
Provide () { 
    return { 
      thisObj: this 
    } 
} 

// injection subassembly 
Inject: [ 'thisObj'] 

@ Sun injection assembly 
Inject: [ 'thisObj'] 

// Sun component value modify the parent component 
this.thisObj.showDia =! this.thisObj.showDia

  

Whether nested several levels, to modify the parent component properties are the same wording, it is not very convenient

Guess you like

Origin www.cnblogs.com/diantao/p/11235794.html