首先借鉴官方文档
有时候,非父子关系的两个组件之间也需要通信。在简单的场景下,可以使用一个空的 Vue 实例作为事件总线:
var bus = new Vue()
// 触发组件 A 中的事件
bus.$emit('id-selected', 1)
// 在组件 B 创建的钩子中监听事件
bus.$on('id-selected', function (id) {
// ...
})
具体怎么使用,不多说,直接上代码
首先我们需要在main.js 加入代码,然后对外暴露
var bus = new Vue()
export default bus
然后 main.js就是这样的了
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store/index'
var bus = new Vue()
export default bus
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
准备两个兄弟组件 假如有three.vue 和four.vue 两个组件
------------------------------------
three.vue组件
<template>
<div class="three">
<button @click="change">传递事件</button>
</div>
</template>
<script>
import bus from '../main'
export default {
props: {
outdata: {
type: String,
default: ""
}
},
data() {
return {};
},
methods: {
change() {
// console.log(1)
bus.$emit("outmes", "我是小小!");
}
}
};
</script>
four.vue组件
<template>
<div class="four">
{{message}}
</div>
</template>
<script>
import bus from '../main'
export default {
data() {
return {
message: "我是组件4"
};
},
//需要在生命周期 mounted 钩子函数里监听来自bus的事件outmes
mounted() {
let _this = this
bus.$on("outmes", function(mes) {
console.log(mes);
_this.message = mes;
});
}
};
</script>
<style scoped>
</style>