Detailed explanation of communication method between parent and child components in vuejs

Time:2020-4-17

This paper introduces the communication method between parent and child components in vuejs. To share with you for your reference, as follows:

1、 Parent passes messages to child

// Parent.vue

<template>
 <div>
  <v-child :msg="message"></v-child>
 </div>
</template>
<script>
 import VChild from './child.vue'
 export default {
  components: {
   VChild
  },
  data () {
   return {
    //The parent component passes message as a parameter to the child component
    Message: 'from parent component message'
   }
  }
 }
</script>
// Child.vue
<template>
 <div>
  <h1>child</h1>
  <p>{{ msg }}</p>
 </div>
</template>
<script>
 export default {
  //Define parameters that can be passed in by external system through props
  //A msg variable is defined. The type is string, and the default is empty string
  props: {
   msg: {
    type: String,
    default: ""
   }
  }
 }
</script>

// router/index.js

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Parent from '@/test/Parent'
Vue.use(Router)
export default new Router({
 routes: [
  {
   path: '/',
   name: 'HelloWorld',
   component: HelloWorld
  },
  {
   path: '/parent',
   component: Parent
  }
 ]
})

2、 Child component passing message to parent component

// Parent.vue

<template>
 <div>
  <v-child :msg="message" @childNotify="childNotify"></v-child>
 </div>
</template>
<script>
 import VChild from './child.vue'
 export default {
  components: {
   VChild
  },
  data () {
   return {
    //The parent component passes message as a parameter to the child component
    Message: 'from parent component message'
   }
  },
  methods: {
   childNotify (params) {
    console.log(params)
   }
  }
 }
</script>
// Child.vue

<template>
 <div @click="notifyParent">
  <h1>child</h1>
  <p>{{ msg }}</p>
 </div>
</template>
<script>
 export default {
  //Define parameters that can be passed in by external system through props
  //A msg variable is defined. The type is string, and the default is empty string
  props: {
   msg: {
    type: String,
    default: ""
   }
  },
  methods: {
   notifyParent () {
    var params = {
     m: 1,
     n: 2
    }
    //The child notifies the parent as an event (you need to use the $emit method, the first parameter, the name of the event; the parameter attached to the second event)
    this.$emit('childNotify', params)
   }
  }
 }
</script>

Reference resources:https://jingyan.baidu.com/article/455a99505b639da1662778e1.html

I hope this article will be helpful to the program design of vue.js.