1.新建一个eventBus.js
import Vue from 'vue'
export default new Vue()
2.brother1.vue(发送方)
import引入bus
import bus from './eventBus'
自定义一个emit事件
bus.$emit('share',this.msg);
<template>
<div>
<button @click="sendMessage">发送消息</button>
</div>
</template>
<script>
import bus from './eventBus'
export default {
data() {
return {
msg:'cfy的message',
}
},
methods:{
sendMessage(){
bus.$emit('share',this.msg);
}
}
}
</script>
<style>
</style>
3.brother2.vue(接收方)
import引入bus
import bus from './eventBus'
接收这个emit事件
<template>
<div>
{{msgFromLeft}}
</div>
</template>
<script>
import bus from './eventBus'
export default {
data() {
return {
msgFromLeft:''
}
},
created(){
bus.$on('share',val=>{
this.msgFromLeft = val
})
},