vue中父子组件通信

父子组件之间进行通信的方式如下:

父子通信:通过props向子组件传递数据
子父通信:通过事件向父组件发送消息 

1.父组件向子组件传递消息

props的值有两种方式:
方式一:字符串数组,数组中的字符串就是传递时的名称。
方式二:对象,对象可以设置传递时的类型,也可以设置默认值等。

// 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
    }
  ]
})

 2.子组件向父组件传递信息

自定义事件的流程:
在子组件中,通过$emit('事件名称','传递的参数')来触发事件。
在父组件中,通过v-on来监听子组件事件。

// 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>

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值