效果
- dad 发送消息
- son发送消息
步骤
- 在 main.js 挂载事件总线 Bus
- $emit(‘事件名’,‘值’)
- $on(‘事件名’,value =>{ 接收value })
方法
方法1
- main.js
Vue.prototype.bus = new Vue()
- 父组件
<template>
<div class="dad">
<input type="text " v-model="dad" />
<button @click="sendMsg">dad发送消息</button>
<div>接收son消息:{{son}}</div>
<son></son>
<girl></girl>
</div>
</template>
<script>
import son from './son.vue'
import girl from './girl.vue'
export default {
components: {
son,
girl
},
mounted() {
this.bus.$on('child', value => {
this.son = value
})
},
data() {
return {
dad: '', // 父组件发送的信息
son: '' // 儿子发送的信息
}
},
methods: {
sendMsg() {
this.bus.$emit('parent', this.dad)
}
}
}
</script>
<style>
.dad {
background-color: antiquewhite;
width: 500px;
height: 500px;
transform: translate(50%);
}
</style>
- son组件
<template>
<div>
<div class="box">
<h4>接收dad消息:{{dad}}</h4>
<input type="text" v-model="son">
<button @click="sendMsg">son发送消息</button>
</div>
</div>
</template>
<script>
// import bus from './event'
export default {
data() {
return {
dad: '默认',
son:''
}
},
mounted() {
this.bus.$on('parent', value => {
this.dad = value
})
},
methods:{
sendMsg(){
this.bus.$emit('child',this.son)
}
}
}
</script>
<style>
.box {
background-color: pink;
height: 200px;
width: 200px;
}
</style>
- girl组件
<template>
<div>
<div class="girl">
<h4>接收dad消息:{{dad}}</h4>
<h4>接收son消息:{{son}}</h4>
</div>
</div>
</template>
<script>
// import bus from './event'
export default {
data() {
return {
dad: '',
son:''
}
},
mounted() {
this.bus.$on('parent', value => {
this.dad = value
})
this.bus.$on('child', value => {
this.son = value
})
}
}
</script>
<style>
.girl {
background-color: rgb(206, 234, 245);
width: 200px;
height: 200px;
}
</style>
方法2
只是挂载方法不同,所以只放 main.js 部分,其他部分见方法1。
new Vue({
render: h => h(app),
beforeCreate () {
// 安装全局事件总线
Vue.prototype.bus = this
}
}).$mount('#app')
方法3
此方法没有全局挂载,但挂载方式不同,且使用时不需加 this 。
所以此处只放 dad 页面,以示 bus 使用方法。
- 新建event.js
import Vue from 'vue'
export default new Vue()
- dad
1)导入import bus from './event'
2)使用bus.$on
或bus.$emit
<template>
<div class="dad">
<input type="text " v-model="dad" />
<button @click="sendMsg">dad发送消息</button>
<div>接收son消息:{{son}}</div>
<son></son>
<girl></girl>
</div>
</template>
<script>
import son from './son.vue'
import girl from './girl.vue'
import bus from './event'
export default {
components: {
son,
girl
},
mounted() {
bus.$on('child', value => {
this.son = value
})
},
data() {
return {
dad: '', // 父组件发送的信息
son: '' // 儿子发送的信息
}
},
methods: {
sendMsg() {
bus.$emit('parent', this.dad)
}
}
}
</script>
<style>
.dad {
background-color: antiquewhite;
width: 500px;
height: 500px;
transform: translate(50%);
}
</style>