当前位置: 首页 > 工具软件 > tinyscript > 使用案例 >

Vue3使用tiny-emitter实现兄弟组件传参

陆畅
2023-12-01
  1. 下载tiny-emitter
npm i tiny-emitter
  1. 创建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),
};
  1. 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");

  1. 兄弟组件中使用
// 发布数据端
<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>
 类似资料: