1.父組件 father.vue
<template>
<div id="father">
<h2>父組件</h2>
<p>數值:{{m}}</p>
<son1 v-on:giveFather='giveFather'></son1>
<son2></son2>
</div>
</template>
<script>
import son1 from './son1'
import son2 from './son2'
export default {
data(){
return {
m:''
}
},
name:'father',
components:{
son1,
son2
},
methods:{
giveFather: function(childValue) {
// childValue就是子組件傳過來的值
this.m = childValue
}
}
}
</script>
2.子組件1 son1.vue
<template>
<div id="son1">
<h2>子組件1</h2>
<button @click='push'>向兄弟組件傳值</button>
<button @click='give'>向father組件傳值</button>
</div>
</template>
<script>
import bus from '../../assets/eventBus'
export default {
methods:{
push(){
bus.$emit("userDefinedEvent","this message is from son1 to son2");
},
give(){
this.$emit('giveFather',"this message is from son1 to father")
}
}
}
</script>
3.子組件2 son2.vue
<template>
<div id="son2">
<h2>子組件2</h2>
<p>數值:{{msg}}</p>
</div>
</template>
<script>
import bus from '../../assets/eventBus'
export default {
data(){
return {
msg:''
}
},
mounted(){
var self = this;
bus.$on("userDefinedEvent",function(msg){
self.msg=msg;
});
}
}
</script>
4.中央事件總線
同級組件傳值時,需要添加中央數據總線 在src/assets/下創建一個eventBus.js,內容如下
(eventBus中我們只創建了一個新的Vue實例,以后它就承擔起了組件之間通信的橋梁了,也就是中央事件總線。)
import Vue from 'Vue' export default new Vue
5.效果


5.總結
子組件向父組件傳值時,在響應該點擊事件的函數中使用$emit來觸發一個自定義事件,並傳遞一個參數。在父組件中的子標簽中監聽該自定義事件並添加一個響應該事件的處理方法 ;
同級組件傳值時,用到bus.$emit和bus.$on兩個自定義事件,並需要創建並添加中央數據總線
