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

所属分类: 网络编程 / JavaScript 阅读数: 262
收藏 0 赞 0 分享

本文实例讲述了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程序设计有所帮助。

更多精彩内容其他人还在看

Canvas实现放射线动画效果

本文主要分享了Canvas实现放射线动画的示例代码。具有很好的参考价值,下面跟着小编一起来看下吧
收藏 0 赞 0 分享

微信小程序 image组件binderror使用例子与js中的onerror区别

这篇文章主要介绍了微信小程序 image组件binderror使用例子与js中的onerror区别的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

原生js轮播(仿慕课网)

本文主要分享了原生js实现仿慕课网的轮播效果。具有很好的参考价值,下面跟着小编一起来看下吧
收藏 0 赞 0 分享

Bootstrap table简单使用总结

这篇文章主要为大家总结了Bootstrap table的简单使用方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

微信小程序之MaterialDesign--input组件详解

本篇文章主要介绍了微信小程序之MaterialDesign--input组件详解,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
收藏 0 赞 0 分享

浅析javaScript中的浅拷贝和深拷贝

本篇文章主要介绍了浅析javaScript中的浅拷贝和深拷贝,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

js时间戳和c#时间戳互转方法(推荐)

下面小编就为大家带来一篇js时间戳和c#时间戳互转方法(推荐)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Bootstrap模态框使用详解

这篇文章主要为大家详细介绍了Bootstrap模态框的使用方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Jil,高效的json序列化和反序列化库

下面小编就为大家带来一篇Jil,高效的json序列化和反序列化库。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

BootStrap实现带关闭按钮功能

这篇文章主要介绍了BootStrap实现带关闭按钮功能,非常不错,具有参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多