原理
在 Vue.js 中,父子組件的關系可以總結為 props down, events up 。
父組件通過 props 向下傳遞數據給子組件,子組件通過 events 給父組件發送消息。看看它們是怎么工作的。

業務場景
這里指的是直接父子級關系的通信
- 美女(子組件)將消息發送給大群(父組件)
- 大群(父組件)收到美女發送的消息后再回個信息給美女(子組件)
父組件
template
<template>
<div>
<p>群消息girl:</p>
<div>
{{ somebody }} 說: 我 {{ age }} 了。
</div>
<hr>
<v-girl-group
:girls="aGirls"
:noticeGirl="noticeGirl"
@introduce="introduceSelf"></v-girl-group>
</div>
</template>
注意的點:
- 這里在父組件使用
v-on來監聽子組件上的自定義事件($emit的變化),一旦發生變化noticeGirl方法就會觸發
<script>
import vGirlGroup from './GirlGroup'
export default {
name: 'girl',
components: {
vGirlGroup
},
data () {
return {
aGirls:[{
name:'小麗',
age:22
},{
name:'小美',
age:21
},{
name:'小荷',
age:24
}],
somebody:'',
age:'',
noticeGirl:''
}
},
methods: {
introduceSelf (opt) {
this.somebody = opt.name;
this.age = opt.age;
// 通知girl收到消息
this.noticeGirl = opt.name + ',已收到消息';
}
}
}
</script>
注意的點:
- 這里methods中定義的方法
introduceSelf就是父組件接收到子組件發出的$emit的事件處理程序
子組件
template
<template>
<div>
<ul>
<li v-for="(value, index) in girls">
{{ index }} - {{ value.name }} - {{ value.age }}
<button @click="noticeGroup(value.name,value.age)">發送消息</button>
</li>
</ul>
<div>接收來自大群的消息:{{ noticeGirl }}</div>
</div>
</template>
script
<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>
注意的點:
- 子組件使用
$emit發出自定義事件
相比於Vue1.x的變化:
- $dispatch 和 $broadcast 已經被棄用
*官方推薦的通信方式
- 首選使用Vuex
- 使用事件總線:eventBus,允許組件自由交流
- 具體可見:https://cn.vuejs.org/v2/guide/migration.html#dispatch-和-broadcast-替換
結果



