- 下载tiny-emitter
npm i tiny-emitter
- 创建utils文件夹中bus.js
import emitter from "tiny-emitter/instance";
export default {
$on: (...args) => emitter.on(...args),
$once: (...args) => emitter.once(...args),
$off: (...args) => emitter.off(...args),
$emit: (...args) => emitter.emit(...args),
};
- main.js里面导入注册
import { createApp } from "vue";
import App from "./App.vue";
import $bus from "./utils/bus";
let app = createApp(App);
app.config.globalProperties.$bus = $bus;
app.mount("#app");
- 兄弟组件中使用
// 发布数据端
<script>
export default {
data() {
return {
song: "我是兄弟组建的数据",
};
},
methods: {
handleBro() {
//发布数据
this.$bus.$emit("getBro", this.song);
},
},
};
</script>
// 订阅数据端
<script>
export default {
data() {
return {};
},
mounted() {
// 订阅事件
this.$bus.$on("getBro", (input) => {
console.log(input);
});
},
};
</script>