How to realize parent-child component communication with Vue

Time:2021-12-31
catalogue
  • 1、 Relationship composition of parent-child components
  • 2、 Props
  • 3、 $emit
  • 4、 $parent
  • 5、 Summary

1、 Relationship composition of parent-child components

This article will summarize the communication between parent and child components in Vue.

What is the relationship between parent and child components in Vue, or which component can be called parent component and which component can be called child component.

In my understanding, the relationship between parent and child components is also relatively simple.

In projects built with Vue cli tools, we often register and reference another component in one component.

Home.vue

<template>
  <div>
    <p>Here is the home component</p>
  </div>
</template>
<script>
export default {
  name: 'Home'
}
</script>
<style scoped>
    .home{
        border:1px solid #4488ff;
        display: inline-block;
        padding: 10px;
    }
</style>

App.vue

<template>
  <div>
    <p>Here is the app component</p>
    <!--  Stpe3: use -- >
    <home></home>
  </div>
</template>

<script>
//Step1: Import
import Home from './components/Home'
export default {
  name: 'App',
  //Step 2: Register
  components: { Home }   
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
  display: inline-block;
  border:1px solid orange;
  padding: 10px;
}
</style>

In the above two components, we introduced, registered and used the home component in the app component.

In Vue, we can call app component as parent component and home component as child component. These two components constitute a parent-child relationship

It must be noted here that the three steps of introduction, registration and use are indispensable.

Otherwise, the two components cannot form a parent-child relationship, nor can they communicate using the communication methods summarized later.

After understanding the composition of parent-child components in Vue, I will introduce how parent-child components communicate before.

2、 Props

The first way of parent-child component communication in Vue is through props attribute, and the parent component communicates with the child component.

Let’s practice the operation.

First, find the place where the child component is used in the parent component, and add the data that the parent component needs to pass to the child component.

App. Vue (omitted part, unmodified code)

<template>
  <div>
    <p>Here is the app component</p>
    <home
        Title = "communication mode between parent and child components in Vue"
        date="2020/03/05 14:25">
    </home>
  </div>
</template>

As you can see, in this step, we added two data to be passed to the sub component where the sub component is used: title and date.

<home
     Title = "communication mode between parent and child components in Vue"
     date="2020/03/05 14:25">
</home>

The next step is to receive these two parameters in the subcomponent using props.

Home. Vue (omitted part, unmodified code)


<script>
export default {
  name: 'Home',
  props: ['title','date']
}
</script>

In the last step, we can use title and date in the subcomponent like Vue data.

Home. Vue (omitted part, unmodified code)

<template>
  <div>
    <p>Here is the home component</p>
    <p>title:{{title}}</p>
    <p>date:{{date}}</p>
  </div>
</template>

After starting the project, view the effect in the browser.

3、 $emit

The second way of parent-child component communication in Vue is through the $emit method, which belongs to the communication between child components and parent components.

The $emit method is an instance method of Vue. Its usage is as follows:

The first parameter eventName is called the event name.

The event corresponding to the event name is a native DOM event monitored by v-on in the parent component (it can be understood as a custom event like click).

When we execute $emit (eventName) in the child component, the corresponding event in the parent component will be triggered.

So first, we use the $emit method in the child component to write code (without passing the second parameter) to trigger the event in the parent component.

Home.vue

<template>
  <div>
    <p>Here is the home component</p>
    <el-button type="primary" v-on:click='btnClickHandler("Yes")'>Yes</el-button>
    <el-button type="primary" v-on:click='btnClickHandler("No")'>No</el-button>
  </div>
</template>
<script>
export default {
  name: 'Home',
  methods: {
    btnClickHandler: function(param){
        if(param == "Yes"){
            this.$emit('sayYes');
        }else if(param == "No"){
            this.$emit('sayNo');
        }
    }
  }
}
</script>

As you can see, there are two buttons in the home subcomponent.

When you click the [yes] button, this will be executed$ Emit (‘sayyes’) to trigger the sayyes event in the parent component.

When [no] button is clicked, this will be executed$ Emit (‘sayno ‘) to trigger the sayNo event in the parent component.

Then we implement the corresponding native DOM event in the parent component.

App.vue  

<template>
  <div>
    <p>Here is the app component</p>
    <home
        v-on:sayYes='val="yes"'
        v-on:sayNo='val="no"'>
    </home>
    <p>val: {{val}}</p>
  </div>
</template>

<script>
import Home from './components/Home'
export default {
  name: 'App',
  data() {
    return {
      val: "default",
    }
  },
  components: { Home },
}
</script>

Sayyes, sayNo are the native DOM events defined in the parent component.


<home
        v-on:sayYes='val="yes"'
        v-on:sayNo='val="no"'>
</home>

Val is a data defined in the parent component. The default value is’ default ‘.

In combination with the code logic of sub components, we know that the following results will be obtained:

When you click the [yes] button, this will be executed$ Emit (‘sayyes’) to trigger the sayyes event in the parent component. In the sayyes event, the Val value in Vue data will be modified to yes.

When [no] button is clicked, this will be executed$ Emit (‘sayno ‘), which triggers the sayNo event in the parent component. In the sayNo event, the Val value in Vue data will be modified to No.

Check our statement in the browser.

4、 $parent

$parent is an instance attribute of Vue, which represents the parent instance of the current component.

If a method in the parent component is sayyes, you can directly use this in the child component$ parent. Sayyes to call the method of the parent component.

App.vue

<template>
  <div>
    <p>Here is the app component</p>
    <home></home>
    <p>val: {{val}}</p>
  </div>
</template>

<script>
import Home from './components/Home'
export default {
  name: 'App',
  data() {
    return {
      val: "default",
    }
  },
  components: { Home },
  methods: {
    sayYes: function() {
      this.val = "yes";
    },
    sayNo: function() {
      this.val = "no";
    }
  }
}
</script>

We define two methods in the parent component: sayyes and sayNo. The logic is: change the value of Val to yes; Change the value of Val to No.

You can then use this in the subcomponent$ parent. Sayyes and this$ parent. SayNo calls the corresponding sayyes and sayNo methods in the parent component.

Home.vue

<template>
  <div>
    <p>Here is the home component</p>
    <el-button type="primary" v-on:click='btnClickHandler("Yes")'>Yes</el-button>
    <el-button type="primary" v-on:click='btnClickHandler("No")'>No</el-button>
  </div>
</template>
<script>
export default {
  name: 'Home',
  methods: {
    btnClickHandler: function(param){
        if(param == "Yes"){
            this.$parent.sayYes();
        }else if(param == "No"){
            this.$parent.sayNo();
        }
    }
  }
}
</script>

The code of the btnclickhandler method in the subcomponent has been changed to this$ Parent is written in this way.

Then we’ll see the results.

5、 Summary

So far, the communication modes of parent-child components in Vue have been summarized. The following methods are summarized respectively:

The first: parent component communicates with child component – props attribute

The second method: the child component communicates with the parent component – $emit method

The third way: the child component communicates with the parent component – $parent attribute

The above is the details of how to use Vue to realize parent-child component communication. For more information about Vue parent-child component communication, please pay attention to other relevant articles of developeppaer!

Recommended Today

Redis featured Q & A

Redis data type type brief introduction characteristic scene String (string) Binary security It can contain any data, such as JPG pictures or serialized objects. One key can store up to 512M It can be used to do the simplest data. It can cache a simple string or a JSON format string. The implementation of redis […]