组件间通讯是组件开发的,咱们既但愿组件的独立性,数据能互不干扰,又不可避免组件间会有联系和交互。html
在vue中,父子组件的关系能够总结为props down,events up;vue
在vue2.0中废弃了$dispatch和$broadcast,子组件使用event发出自定义事件ide
思考场景以下:ui
一个总群(父组件)中你们作自我介绍,this
陌陌、小小、可可、每天 收到 总群发来的消息以后(父传子),将本身的信息发送到总群(子传父)spa
templatecode
<template> <div> <h4>父组件>></h4> <div> <span>{{ somebody }}</span> 说: 我来自 <span>{{ city }} </span> </div> <hr> <!-- aGirls和noticeGirl经过props传递给子组件 --> <!-- introduce经过$emit子组件传递给父组件 --> <v-girl-group :girls="aGirls" :noticeGirl="noticeGirl" @introduce="introduceSelf"></v-girl-group> </div> </template>
我使用的组件间通讯:component
scripthtm
<script> import vGirlGroup from './components/HelloWorld' export default { name: 'girl', components: { vGirlGroup }, data () { return { aGirls:[{ name:'陌陌', city:'GuangZhou' },{ name:'小小', city:'BeiJing' },{ name:'可可', city:'American' },{ name:'每天', city:'HangZhou' }], somebody:'', city:'', noticeGirl:'' } }, methods: { introduceSelf (opt) { this.somebody = opt.name; this.city = opt.city; // 通知girl收到消息 this.noticeGirl = opt.name + ',已收到消息'; } } } </script>
这里的 introduceSelf 就是父组件接收到子组件发出的$emit事件处理程序blog
template
<template> <div> <h4>子组件>></h4> <ul> <li v-for="(value, index) in girls"> {{ index }} - {{ value.name }} - {{ value.city }} <button @click="noticeGroup(value.name,value.city)">发送消息</button> </li> </ul> <div class="msg">接收来自父组件的消息:{{ noticeGirl }}</div> </div> </template>
script
子组件经过$emit发出自定义事件
<script> export default { name: 'girl-group', props: { girls: { type: Array, required: true }, noticeGirl: { type: String, required: false } }, methods: { noticeGroup (name, age) { this.$emit('introduce',{ name: name, age: age }) } } } </script>
到这里,咱们已经根据vue2.0父子间通讯实现了上面提出的一个场景 .
相比vue1.0的变化:具体能够参考:https://cn.vuejs.org/v2/guide/migration.html#dispatch-和-broadcast-替换