vue中可使用bus实现组件间的通信,本文内容为简单案例,即在组件test1中调用组件test2的方法busBrotherAlert2。
1、全局设置main.js
var eventBus = {
install (Vue, options) {
Vue.prototype.$bus = new Vue()
}
};
Vue.use(eventBus);
2、组件test1
<template>
<div>
<el-button @click.prevent="handleClick">我是组件1</el-button>
</div>
</template>
<script>
export default {
name: "test1",
data() {
return {};
},
methods: {
handleClick() {
this.$bus.$emit("busBrotherAlert2", "test");
},
},
};
</script>
3、组件test2
<template>
<div>
<el-button @click.prevent="handleClick">我是组件2</el-button>
</div>
</template>
<script>
export default {
name: "test2",
data() {
return {};
},
mounted() {
this.$bus.$on("busBrotherAlert2", (msg) => {
this.busBrotherAlert2(msg);
});
},
methods: {
busBrotherAlert2(msg) {
console.log(msg);
alert("我是组件一调用组件二的方法");
},
},
};
</script>
4、test.vue
在test中引入test1、test2
<template>
<div>
<test1></test1>
<test2></test2>
</div>
</template>
<script>
import test1 from "./test1.vue";
import test2 from "./test2.vue";
export default {
name: "test",
components: {
test1,
test2,
},
data() {
return {};
},
};
</script>
5、配置路由index.js
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
const router = new Router({
routes: [
......
{
path: "/test",
component: () => import('../views/chart/test.vue'),
},
......
]
})
export default router
6、推荐