Introducing 8 Component Communication Mechanisms in Vue.Js | Vue.Js Interview Questions

By | August 8, 2021

 

This post will summarize 8 component communication mechanisms in Vue.Js. The daily development of component communication is close, and familiarity with component communication can better develop business.

Vue.js Passing values between components

1. The parent component passes the value to the child component

Generally, this involves the following procedures:

  1. Introduce child components in parent components
  2. Register subcomponents
  3. Use in the page, dynamically bind the incoming dynamic value/static value on the sub-component label
  4. In the subcomponent, use props Come to accept the passed parent component value
The value of the parent component received by the child component is divided into two types: reference type and ordinary type:
  • Common types: String, Number, Boolean, Null
  • Reference type: Array, Object
#parent component

<template>
  <div>
    <!-- passing value -->
    <Test
 :obj="obj" 
 info="test"/>
  </div>
</template>

<script>
// Introduce sub-components
import Test from "../components/Test.vue";
export default {
 name: "about",
 // Register child components
 components: {
 Test,
 },
 data() {
 return {
 obj: {
 code: 200,
 title: "Front-end self-study community",
 },
 };
 },
};
</script>


<template>
    <div>
        <h1>{{obj.code}}</h1><br>
        <h2>{{obj.title}}</h2>
        <h3>{{info}}</h3>
    </div>
</template>

<script>
 export default {
 name:'test',
 props:{
 obj:Object,
 info: [String,Number] //info value can be one of the types, other types will report a warning
 }
 }
</script>

due to Vue Is a one-way data flow, Subassembly Cannot be modified directly Parent component Value.

2. The child component passes the value to the parent component

Sub-components through binding events, through this.$emit(&#39;function name&#39;, passing parameters)
#parent component

<Test
 :obj="obj" 
 info="test"
 @modify="modifyFatherValue"/>

<script>
// Introduce sub-components
import Test from "../components/Test.vue";
export default {
 name: "about",
 // Register child components
 components: {
 Test,
 },
 data() {
 return {
 msg:&#39;I am the parent component&#39;
 };
 },
 methods:{
 // Accept the value passed by the subcomponent and assign it to the attribute in the data
 modifyFatherValue(e){
 this.msg = e
 }
 }
};
</script>

# child component

<button @click="modifyValue">modifiy the value of the parent component</button>


<script>
 export default {
 name:'test',
 methods:{
 modifyValue(){
 this.$emit('modify',&#39;The value passed by the child component&#39;)
 }
 }
 }
</script>

3. The parent component passes $refs / $children To get the sub-component value

$refs :
  • Obtain DOM elements and component instances to obtain component properties and methods.
  • By binding on child components ref ,use this.$refs.refName. sub-component properties / sub-component methods
$children :
  • The sub-components of the current instance, it returns a collection of sub-components. If you want to get which component properties and methods, you can pass this.$children[index]. Child component attribute/f method

Sample Text component

<script>
 export default {
 name:'test',
 data() {
 return {
 datas:"I am a child component value"
 }
 },
 props:{
 obj:Object,
 info: [String,Number]
 },
 methods:{
 getValue(){
 console.log(&#39;I am Test1&#39;)
 }
 }
 }
</script>

Example Text2 component

<template>
    <div>
        <h1>I'm Test2</h1>
    </div>
</template>

<script>
 export default {
 name:'test',
 data() {
 return {
 datas:"I am Test2"
 }
 },
 created(){
 console.log( this.$parent.obj ) 
 this.$parent.getQuery()
 },
 methods:{
 getTest2(){
 console.log(this.datas)
 }

 }
 }
</script>

refs

<template>
  <div>
   // binding ref  
    <Test
 ref="son"
 />
   <Test2/>
  </div>
</template>


 console.log( this.$refs.son.datas) 

 this.$refs.son.getValue()

$children

// Get the properties and methods of child components through $children
      this.$children[0].getValue(); // I am Test1
      this.$children[1].getTest2();  //I’m Test2
      console.log(`---------${this.$children[1].datas}`); //I’m Test2

4. Sub-components passed $parent To get the properties and methods of the parent component instance

<script>
 export default {
 name:'test',
 created(){
 console.log( this.$parent.obj ) 
 this.$parent.getQuery()
 },

 }
</script>

5. $attrs And $listeners Get the properties and methods of the parent component instance (used in the case of nested components)

$attrs : Contains not considered in the parent scope (and not expected to be) props The feature binding (except class and style), and can pass v-bind=” $attrs “Into the internal components. When a component does not declare any props At the time, it contains all the bindings of the parent scope (except class and style). $listeners : Contains the v-on event listener in the parent scope (without the .native modifier). It can be passed v-on=” $listeners “Pass in the internal component. It is an object that contains all event listeners acting on this component, which is equivalent to the child component inheriting the event of the parent component.

Use scenario: Use in the case of multi-layer nested components, you can avoid using Vuex for data processing, use v-bind=”$attrs” v-on=”$listeners” It is very convenient to achieve business data transfer.

Parent component

<template>
    <div>
        <Test3 
 :status="status" 
 :title="title"
 @getData="getData" />
    </div>
</template>

<script>
import Test3 from "../components/Test3.vue";
 export default {
 name:'person',
 data(){
 return {
 title:&#39;personal component&#39;,
 status: false
 }
 },
 methods:{
 getData(){
 console.log(this.title)
 } 
 },
 components:{
 Test3
 }
 }
</script>

Subcomponent 1

<template>
  <div>
    <h1>Test3 Component</h1>
    <br /><br />
    <Test4 v-bind="$attrs" v-on="$listeners"/>
  </div>
</template>

<script>
// Introduce sub-components
import Test4 from "../components/Test4";
export default {
 name: "test3",
 props: ["title"],
 components: {
 Test4,
 },
 created() {
 console.log(this.$attrs); //{status: false}
 console.log("-----------");
 console.log(this.$listeners); // {getData: ƒ}
 },
};
</script>

Nested subcomponents

<template>
    <div>
        <h1>Test4 Component</h1>
    </div>
</template>

<script>
 export default {
 name:'test4',
 created(){
 console.log('-----Test4------')
 console.log(this.$attrs) //{status: false}
 console.log(this.$listeners) // {getData: ƒ}
 }
 }
</script>

6. Passing values between components

By creating a new one js File, import vue , Export vue Instance; then bind events to the exported instance $emit Event, and then pass $on Monitor the triggered event, so that you can achieve global component data sharing.

scenes to be used:

It can meet any scenario to transfer data, Parent-child component pass value , Pass-by-value , Passing values between sibling components , Passing values between cross-level components .

When the communication data is relatively simple, this solution can be adopted, and the project is relatively large, and it can be adopted Vuex .

vue .js

 import Vue from 'vue'

 export default new Vue()

Component A

<template>
    <div>  
        <button @click="changeValue">Modify</button>
    </div>
</template>

<script>
import zxVue from '../util/newVue.js';
 export default {
 name:'person',
 data(){
 return {
 title:&#39;personal component&#39;,
 status: false
 }
 },
 methods:{
 changeValue(){
 // By binding events to the vue instance
 zxVue.$emit("getTitle", this.title) 
 } 
 }
 }
</script>




Component C

<!--
 * @Description: 
 * @Author: ZhangXin
 * @Date: 2021-01-22 15:07:30
 * @LastEditTime: 2021-01-22 16:26:38
 * @LastEditors: ZhangXin
-->
<template>
  <div>
    <h1>Test4 Component</h1>
    <h1>{{ title }}</h1>
  </div>
</template>

<script>
import zxVue from "../util/newVue";
export default {
 name: "test4",
 data() {
 return {
 title: "test4",
 };
 },
 mounted(){
 // Use the vue instance.$on to listen to the event name to receive the value passed by the cross-level component
 zxVue.$on("getTitle", (item) => {
 this.title = item;
 console.log(item)
 });

 }
};
</script>


7. Vuex

Since Vuex is evolving really fast, please refer to the official documentation.

8. provide And inject Realize the parent component to pass values to the descendant components. (Unlimited level)

provide And inject This pair of options need to be used together to allow an ancestor component to inject a dependency into all its descendants, no matter how deep the component level is, and it will always take effect when the upstream and downstream relationship is established. provide :
  • Is an object or a function that returns an object
  • This object contains properties that can be injected into its descendants.
inject :
  • Is an array of strings or an object
  • Used to inject in subcomponents or descendant components provide Provide the properties of the parent component.

scenes to be used:

Provide/inject can easily achieve cross-level access to the data of the parent component
# provide
//object
provide:{
    name:&#39;test&#39;
}
//The function that returns the object
provide(){
    return {
        name: &#39;test&#39;
    }
}

#inject
inject:['name']

Parent component

<template>
    <div>
        <h1>Parent Component</h1>
        <Son />
    </div>
</template>

<script>
import Son from '../components/son/SonOne'
 export default {
 name:'father',
 provide(){
 return {
 titleFather: &#39;The value of the parent component&#39;
 }
 },
 components:{
 Son
 },
 data(){
 return{
 title:&#39;I am the parent component&#39;
 }
 },

 }
</script>



Subassembly

<template>
    <div>
        <h1>Child Component</h1>

    </div>
</template>

<script>
import SonTwo from '../son/SonTwo'
 export default {
 name:'sonone',
 components:{
 SonTwo
 },
 inject:['titleFather'],
 created(){
 console.log(`${this.titleFather}-----------SonTwo`)
 },
 data(){
 return{
 title:&#39;I am a child component&#39;
 }
 },

 }
</script>

Descendant components

<template>
    <div>
        <h1>Child Component</h1>

    </div>
</template>

<script>
import SonTwo from '../son/SonTwo'
 export default {
 name:'sonone',
 components:{
 SonTwo
 },
 inject:['titleFather'],
 created(){
 console.log(`${this.titleFather}-----------SonTwo`)
 },
 data(){
 return{
 title:&#39;I am a child component&#39;
 }
 },

 }
</script>