vue 2.0 Communication Methods between Parent and Child Components and Non Parent and Child Components

  • 2021-07-13 03:59:21
  • OfStack

1. Parent component passes data to child component

How is parent component data passed to child components? It can be implemented by props attribute

Parent component:


<parent>
  <child :child-msg="msg"></child>// It must be used here  -  Instead of hump 
</parent>
data(){
  return {
    msg: [1,2,3]
  };
}

Subcomponents receive data through props:

Mode 1:


props: ['childMsg']

Mode 2:


props: {
  childMsg: Array // This allows you to specify the type passed in and warn if the type is wrong 
}

Mode 3:


props: {
  childMsg: {
    type: Array,
    default: [0,0,0] // This allows you to specify a default value 
  }
}

In this way, the parent component passes data to the child component.

2. Child component communicates with parent component

So, what if the subcomponent wants to change the data? This is not allowed in vue, because vue only allows one-way data transfer. At this time, we can notify the parent component to change the data by triggering events, so as to achieve the purpose of changing the data of the child component.

Subcomponents:


<template>
  <div @click="up"></div>
</template>
methods: {
  up() {
    this.$emit('upup','hehe'); // Active trigger upup Method, 'hehe' For the data passed to the parent component 
  }
}

Parent component:


<div>
  <child @upup="change" :msg="msg"></child> // Event triggered by a listening subcomponent upup Events , And then call change Method 
</div>
methods: {
  change(msg) {
    this.msg = msg;
  }
}

3. Non-parent component communication

How do two components communicate if they are not parent and child components? At this time, communication can be realized through eventHub.
The so-called eventHub is to create an event center, which is equivalent to a transit station, and can be used to transmit and receive events.


let Hub = new Vue(); // Create an event center 

Component 1 triggers:


<div @click="eve"></div>
methods: {
  eve() {
    Hub.$emit('change','hehe'); //Hub Trigger event 
  }
}

Component 2 receives:


<div></div>
created() {
  Hub.$on('change', () => { //Hub Receive event 
    this.msg = 'hehe';
  });
}

In this way, the communication between non-parent and child components is realized. The principle is to treat Hub as a transit station!


Related articles: