当前位置: 移动技术网 > IT编程>开发语言>JavaScript > vuejs中父子组件之间通信方法实例详解

vuejs中父子组件之间通信方法实例详解

2020年03月09日  | 移动技术网IT编程  | 我要评论

本文实例讲述了vuejs中父子组件之间通信方法。分享给大家供大家参考,具体如下:

一、父组件向子组件传递消息

// parent.vue

<template>
 <div class="parent">
  <v-child :msg="message"></v-child>
 </div>
</template>
<script>
 import vchild from './child.vue'
 export default {
  components: {
   vchild
  },
  data () {
   return {
    // 父组件将message作为参数传入子组件中
    message: '来自父组件消息'
   }
  }
 }
</script>

// child.vue
<template>
 <div class="child">
  <h1>child</h1>
  <p>{{ msg }}</p>
 </div>
</template>
<script>
 export default {
  // 通过props定义外部系统可以传入的参数
  // 定义了一个msg变量,类型是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
  }
 ]
})

二、子组件向父组件传递消息

// parent.vue

<template>
 <div class="parent">
  <v-child :msg="message" @childnotify="childnotify"></v-child>
 </div>
</template>
<script>
 import vchild from './child.vue'
 export default {
  components: {
   vchild
  },
  data () {
   return {
    // 父组件将message作为参数传入子组件中
    message: '来自父组件消息'
   }
  },
  methods: {
   childnotify (params) {
    console.log(params)
   }
  }
 }
</script>

// child.vue

<template>
 <div class="child" @click="notifyparent">
  <h1>child</h1>
  <p>{{ msg }}</p>
 </div>
</template>
<script>
 export default {
  // 通过props定义外部系统可以传入的参数
  // 定义了一个msg变量,类型是string,默认是空字符串
  props: {
   msg: {
    type: string,
    default: ""
   }
  },
  methods: {
   notifyparent () {
    var params = {
     m: 1,
     n: 2
    }
    // 子组件以事件的形式通知父组件(需要使用$emit方法,第一个参数,事件名称;第二个事件附带的参数)
    this.$emit('childnotify', params)
   }
  }
 }
</script>

参考:https://jingyan.baidu.com/article/455a99505b639da1662778e1.html

希望本文所述对大家vue.js程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网