在小项目中如果组件间层级嵌套很深的时候可以使用bus来调用其他组件的方法
代码实现:
1、新建一个bus.js文件,如下代码import Vue from "vue"; export default new Vue();
2、在组件1中
<template>
<div class="bus-brother1">
<el-button @click.prevent="handleClick">我是组件1</el-button>
</div>
</template>
<script>
import bus from "@/store/bus"
export default {
data() {
return {
}
},
mounted() {
bus.$on("busBrotherAlert1", () => {
this.busBrotherAlert1()
})
},
methods: {
handleClick () {
bus.$emit("busBrotherAlert2")
},
busBrotherAlert1() {
alert('我是组件二调用组件一的方法')
}
}
}
</script>
3、在组件2中
<template>
<div class="bus-brother2">
<el-button @click.prevent="handleClick">我是组件2</el-button>
</div>
</template>
<script>
import bus from "@/store/bus"
export default {
data() {
return {
}
},
mounted() {
bus.$on("busBrotherAlert2", () => {
this.busBrotherAlert2()
})
},
methods: {
handleClick() {
bus.$emit("busBrotherAlert1")
},
busBrotherAlert2() {
alert('我是组件一调用组件二的方法')
}
}
}
</script>