# 父子组件之间的通信(props down, events up)
1、父组件向子组件传递(props down )
app.vue(父组件)
<template>
<div id="app">
<hello :text="msg"></hello>
</div>
</template>
<script>
import hello from '@/components/hello'
export default {
name: 'app',
data (){
return {
msg: "I come from parent"
}
},
components:{
hello
},
}
</script>
hello.vue(子组件)
<template>
<div class="hello">
<button type="button">{{ text }}</button>
</div>
</template>
<script>
export default {
name: 'hello',
data () {
return {
msg: "I come from child"
}
},
props:[ 'text' ]
}
</script>
如图所示,按钮显示的信息来自父组件:

2、子组件向父组件传递(events up)
子组件通过this.$emit("事件名",参数)触发自定义事件
app.vue(父组件):
<template>
<div id="app">
<p>来自子组件的内容:<span>{{ msg}}</span></p>
<hello @get-msg-from-child="getMsg"></hello>
</div>
</template>
<script>
import hello from '@/components/hello'
export default {
name: 'app',
data (){
return {
msg: ""
}
},
components:{
hello
},
methods: {
getMsg (a){
this.msg = a;
}
}
}
</script>
hello.vue(子组件):
<template>
<div class="hello">
<button type="button" @click="showMsg">点我</button>
</div>
</template>
<script>
export default {
name: 'hello',
data () {
return {
msg: "I come from child"
}
},
methods: {
showMsg (){
this.$emit('get-msg-from-child',this.msg)
}
}
}
</script>
点击“点我按钮”,会显示获取到的子组件的内容:

# 非父子组件通信
在简单的场景下,可以使用一个空的 Vue 实例作为中央事件总线; 在复杂的情况下,我们应该考虑使用专门的状态管理模式.(这里不涉及)。
bus.js:
import Vue from 'vue'
var bus = new Vue();
export { bus }
app.vue(含有aaa和bbb组件):
<template>
<div id="app">
<aaa></aaa>
<bbb></bbb>
</div>
</template>
<script>
import aaa from '@/components/aaa'
import bbb from '@/components/bbb'
export default {
name: 'app',
components:{
aaa,
bbb
}
}
</script>
aaa.vue:
<template>
<div class="a">
aaa的输入框: <input v-model="msg" @keyup="changeMsg">
</div>
</template>
<script>
// 引入bus
import {bus} from './bus.js'
export default {
data () {
return {
msg: ""
}
},
methods: {
changeMsg (){
// 触发事件
bus.$emit("get-aaa-msg", this.msg)
}
}
}
</script>
bbb.vue:
<template>
<div class="b">
<p>bbb的内容:<span>{{msg}}</span></p>
</div>
</template>
<script>
import {bus} from './bus.js'
export default {
data () {
return {
msg: ""
}
},
mounted (){
// 自定义事件
bus.$on("get-aaa-msg", (msg) => {
this.msg = msg
})
}
}
</script>
显示结果如下:

当在aaa中输入内容,会在下面显示出来获取到的数据,如下:

