Front end interview Vue part (5) — what are the communication methods between Vue components

Time:2020-9-29

file

What are the communication methods between Vue components (SSS)

图片

Common usage scenarios can be divided into three categories:

  • Parent child communication:

    • null
      Parents pass data to their children throughpropsFrom the son to the father$emit / $on
    • $emit / $bus
    • Vuex
    • Communication is also possible through the parent chain / child chain($parent / $children
    • refYou can also access component instances
  • Brother Communications:

    • $emit / $bus
    • Vuex
  • Cross level communication:

    • $emit / $bus
    • Vuex
    • provide / inject API
    • $attrs/$listeners

$emit / $bus

// main.js 
Vue.prototype . $bus = new vue() // event bus is used for communication between unrelated components.

A triggers B

//  A 
 this.$bus.$emit('new-messsage-at-me', { 
    data: { conversationID: message.conversationID } 
  })
//  B 
  mounted() { 
    this.$bus.$on('new-messsage-at-me', event => { 
      if ( 
        event.data.conversationID === this.conversation.conversationID && 
        this.conversation.conversationID !== 
          this.currentConversation.conversationID 
      ) { 
        this.hasMessageAtMe = true 
      } 
    }) 
  },

Communication between parent and child components

  1. Parent component passes value to child component( props ):
// App.vue Parent component 
 
   
    //In the former, the user-defined name is convenient for the sub component to call, while the latter needs to pass the data name 
   
 
 
import Users from "./components/Users" 
export default { 
  name: 'App', 
  data(){ 
    return{ 
      users:["Henry","Bucky","Emily"] 
    } 
  }, 
  components:{ 
    "users":Users 
  } 
} 
</code></code></pre>
< pre > < code > < code > // users sub component  
//Note: there are three forms of data in components: data, props, and computed 
<template> 
  <div class="hello"> 
    <ul> 
      < Li V-for = "user in users" > {user}} < / Li > // traverse the values passed in, and then render them to the page 
    </ul> 
  </div> 
</template> 
<script> 
export default { 
  name: 'HelloWorld', 
  props:{ 
    Users: {// this is the child tag custom name of the parent component 
      type:Array, 
      required:true 
    } 
  } 
}
  1. Pass value from child component to parent component ($emit in component B, v-on in component a)
//Sub components 
 
   
    {Title}} // bind a click event 
   
 
 
export default { 
  name: 'app-header', 
  data() { 
    return { 
      title:"Vue.js Demo" 
    } 
  }, 
  methods:{ 
    changeTitle() { 
      This. $emit ("titlechanged", "child passes value to parent component"); // custom event passes value "child passes value to parent component" 
    } 
  } 
}
//Parent component 
 
   
    //Consistent with sub component titlechanged custom event 
   //Updatetitle ($event) accepts the text passed in 
    {{title}} 
   
 
 
import Header from "./components/Header" 
export default { 
  name: 'App', 
  data(){ 
    return{ 
      Title: "passed a value" 
    } 
  }, 
  methods:{ 
    Updatetitle (E) {// declares this function 
      this.title = e; 
    } 
  }, 
  components:{ 
   "app-header":Header, 
  } 
}

$ref and $parent $children

  • Use this. $parent to find the parent of the current component.
  • Use this. $children to find the direct sub components of the current component. You can traverse all the sub components. Note that $children does not guarantee the order and is not responsive.
  • Use this. $root to find the root component, and can cooperate with $children to traverse all components.
  • Use this. $refs to find named subcomponents( )( this.$refs.one )

$attrs / $listeners

  • The emergence of both makes the cross component communication between components simple and clear without relying on vuex and event bus.
  • When a – > b – > C multi-level component nesting needs to transfer data, the commonly used method is through vuex. If we just transfer the data, and do not do the intermediate processing, using vuex processing, it would be a bit of killing chicken with a knife. Vue version 2.4 provides another method, which uses v-bind = “$attrs” to transfer the attributes in the parent component that are not considered to be bound by props attribute into the child component, which is usually used with the interitattrs option.
  • To put it simply: $attrs and $listeners are two “objects”. The non props attributes bound in the parent component are stored in $attrs. The only drawback is that the attributes not defined in props will be displayed on the generated HTML tags. Solution: through inh eritAttrs:false To avoid the top-level container inheriting properties; $listeners stores non-native events bound in the parent component.

A parent component

import childDom from "@/components/ChildDom.vue"; 
 export default { 
   name:'demoNo', 
   data() { 
     return { 
       foo:"Hello, world", 
        coo:"Hello,rui" 
    } 
  }, 
 components:{childDom}, 
 methods:{ 
   reciveRocket(){ 
      console.log("reciveRocket success") 
   } 
 } 
}

Sub assembly B

foo:{{foo}} 
     attrs:{{$attrs}} 
      
    
 
 
import childDomChild from './childDomChild'; 
export default { 
   name:'child-dom' 
   props:["foo"], 
   inheritAttrs:false, 
}

Sub components of C sub component

coo:{{coo}} 
       I'm going to launch a rocket 
    
 
 
 export default { 
   name:'childDomChild', 
   props:['coo'], 
   methods:{ 
     startUpRocket(){ 
       this.$emit("upRocket"); 
       console.log("startUpRocket") 
     } 
   } 
 }

provide / inject

  • It is suitable for the communication of intergenerational components. The ancestor component provides variables through provider, and then injects variables into descendant components. The provide / inject API mainly solves the communication problem between cross level components. However, its usage scenario is that the sub components get the status of the superior components, and a relationship between active provision and dependency injection is established between cross level components.
  • If it is a single use of data, defined in the parent component, it can be used in all child components
  • The official website does not recommend using this method directly in the application, the reason is very direct: he is afraid that you “can’t manage well”

1. Generally, it is used in app.vue Configured as:

provide () { 
  return { 
    isTest: this 
  } 
},

2. All sub components can be obtained by reference app.vue All the data in it

inject: ['isTest'],

Welcome to leave a message~~~