Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

Using vue.js to communicate between project development components is an essential knowledge point. As components are an important module in vUE, and each component has its own independent scope, data transfer between components becomes especially important. (Data-driven view. It doesn’t matter what you say ~ hey!

Relationship between components

As shown above

Component A contains component B and component C so you can call this parent-child component relationship what about B and C? B and C can be called sibling component relationshipsB->D C->ECan be called parent-child component relationshipsD->EThis is called a sibling component relationshipA-D A-EThis is called the grandparent component relationship so we can divide it into two types

Communication between parent and child components Communication between non-parent and child components (grandparent relationship, sibling relationship)Copy the code

After understanding the above relationship, we will expand it by classification.

Communication between parent and child components

There are three communication methods between parent and child components in Vue, as follows:

1. Props ->$emit 2.$parent->$children 3. Provide ->injectCopy the code

1.props -> $emit

As one of the most commonly used communication methods of Vue, I think everyone is familiar with it. This is the most recommended communication method of parent-child component relationship on the Vue official website. Vue has made a complete implementation to make it very convenient for us to communicate between parent-child components

// ComponentA(parent component)
<template>
 <div class="fruit_shop">
 <component-b 
 @remove="handleRemove"
 :fruitList="fruitList" />
 </div>
</template>

<script>
import componentB from './test/componentB.vue'
export default {
 name'ComponentA'.components: { componentB },
 data() {
    return {
        fruitList: ['apple'.'banana'.'watermelon']}},method: {handleRemove(params){
     this.fruitList.splice(params,1)}}}</script> 
Copy the code
// componentB(subcomponent)
<template>
 <div>
 <span v-for="(item, index) in fruitList" @click="$emit('remove',index)" :key="index">{{item}}</span>
 </div>
</template>
 
<script>
export default {
 props: ['fruitList']}</script>
Copy the code

The parent component passes the fruitList to the child component via v-bind and the child component uses props to accept the fruitList passed to the parent component and then iterate over the render. We add a click event to the span tag that triggers the child component to communicate with the parent component.

// Subcomponent //'remove' indicates the name to communicate and index indicates the parameter to communicate. Parameters can be of any type. $emit('remove',index) // Parent component receives communication from child component and calls corresponding event method @remove="hanldeRemove"Copy the code

Summary: PROP can only be passed from parent to child. The data is one-way data flow.

2.$parent-> $child

The second way for vue’s parent components to communicate is $parent and $child. $parent fetches all parent instances of the current parent component.

// ComponentA(parent component)
<template>  
<div class="fruit_shop">
<span>{{message}}</span>
<component-b />
<button @click='changeChildMsg'>Modifies the value of the child component</button>
</div> 
</template> 
<script> 
import componentB from './test/componentB.vue'
export default {
  name'ComponentA'.components: { componentB }, 
  data() { 
    return {  
      message:'hello world! '}},method: {changeChildMsg(){
       this.$child[0].childMsg ='hello, the child Component. '}}}</script>
Copy the code
// componentB(subcomponent)
<template> 
<div>  
<hr/>
<span>{{parentMsg}}</span>
</div> 
</template>
<script>
export default{  
 name:'ComponentB'.data(){
   return {
     childMsg:'hello, the parent Component. '}},computed: {parentMsg(){
         return this.$parent.message
       }
    }
  </script>
Copy the code

As shown in the code above, the child Component gets message from the parent Component instance through a computed property. The parent modifies childMsg in the child Component instance through a click event and changes it to ‘Hello Child Component! $parent is an object, and $child is an array. Summary for large VUE projects: For large VUE projects, components are intertwined. Using $parent and $child for component communication is not recommended.

3.provide -> inject

Provide and Inject are another means of component communication provided by VUE but are not limited to communication between parent and child components. Provide We use inject as the receiving side of the variable provided globally by the component.

// componentA. Vue A
<template>
 <div>
    <component-b />
 </div>
</template>
 
<script>
 import ComponentB from '.. /components/componentB.vue'
 export default {
 name"componentA".provide: {
  zoo"bird"
 },
 components:{
  ComponentB
 }
 }
</script>
Copy the code
// componentB. Vue B
<template>
 <div>
 {{animal}}
 <component-c />
 </div>
</template>
 
<script>
 import ComponentC from '.. /components/componentC.vue'
 export default {
 name"componentB".inject: ['zoo'].data() {
  return {
  animalthis.zoo
  }
 },
 components: {
  ComponentC
 }
 }
</script>
Copy the code
// ComponentC.vue C components
<template>
 <div>
 {{demo}}
 </div>
</template>
<script>
 export default {
 name"componentC".inject: ['zoo'].data() {
  return {
  demothis.zoo
  }
 }
 }
</script>
Copy the code

From the above code we can conclude that provide and inject are not only the communication between parent and child components. No matter how deeply nested a component is, as long as it ultimately belongs to ComponentA, inject the Zoo variable provided in ComponentA

The vue. Js document provides an illustration of provide and inject, as shown above. Provide and Inject are non-responsive so provide and inject are suitable for passing some non-dynamic data.

$ref-> $refs

Ref can be used on any DOM or custom components. When used with the browser DOM, you get elements of the DOM. When used with a custom component, you get instances of the component. We can use any method or property in the component by retrieving the component instance

// ComponentA(parent component)
<template>  
<div class="fruit_shop">
<component-b  ref="comb"/>
<button @click='useChildComponent'>Modifies the value of the child component</button>
</div> 
</template> 
<script> 
import componentB from './test/componentB.vue'
export default {
  name'ComponentA'.components: { componentB }, 
   method: {useChildComponent(){
     //refs is the set of all the refs marked by ref. $refs is an object. We get the ref named Comb, which is an instance of component B.
     this.$refs['comb']? .say()// Console prints "Hello,parent Component!"}}}</script>
Copy the code
// componentB(subcomponent)
<template> 
<div>

</div> 
</template>
<script>
export default{  
 name:'ComponentB'.data(){
   return {
     childMsg:'hello, the parent Component. '}},method: {say(){
        console.log(this.childMsg)
        }
      }
    }
  </script>

Copy the code

Conclusion :$refs and $ref are used for communication between parent and child components. Invoke a component’s methods or access data directly from an instance

The last

Communication between parent and child components of Vue component communication ends here. Next time we’ll look at communication between Vue non-parent components

Thank you for watching this blog, if it is helpful to you, I hope to give 👍 comment collection three even!