vue3.0事件总线

Vue3.x以后从实例中移除了 o n , on, onoff 和 o n c e 方 法 , once 方法, onceemit 仍然是现有 API 的一部分,只能实现子组件触发父组件的方法。
使用mitt之前先安装mitt模块

npm install --save mitt或者yarn add mitt -S

然后在程序中使用事件总线:

main.js配置
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
import mitt from 'mitt';引入mitt
let app = createApp(App);
app.config.globalProperties.$bus = new mitt();//绑定事件总线
app.use(store).use(router).mount('#app');


组件一使用:事件绑定
<template>
  <div>
    <h1>About</h1>
  </div>
</template>

<script>
import {getCurrentInstance} from "vue"
export default {
   name: 'About',
   setup () {
    const internalInstance = getCurrentInstance();  //当前组件实例
    const $bus = internalInstance.appContext.config.globalProperties.$bus;
    if(!$bus.all.get("myClick")) $bus.on("myClick",res => {
          console.log(res)
    });
   
    return {
    }
  }
  
}
</script>

<style lang="less" scoped>

</style>




组件二使用:事件触发
<template>
  <div class="hello">
    <button @click="eventFn">事件总线</button>
  </div>
</template>

<script>
import { ref,getCurrentInstance } from "vue";
export default {
  name: "HelloWorld",
  setup() {
    //     vue3.0           vue2.0
    // context.attrs === this.$attrs
    // context.slots === this.$slots
    // context.emit  === this.$emit
     const obj = ref("事件调用成功!");
     const internalInstance = getCurrentInstance(); 
     const $bus = internalInstance.appContext.config.globalProperties.$bus;
     function eventFn(){
      $bus.emit("myClick",obj.value);//事件触发
    }
    return {
      eventFn
    };
  },
};
</script>
<style scoped lang="less">
</style>

注意事项:当我们在绑定事件要注意到,所绑定的事件类型是否存在,如存在那么,就不需要在绑定相同的事件类型了,(因为我们每次进入绑定事件组件时,都会给相同的事件类型,传入不同时间阶段的回调函数,bus.all.get(“myClick”)获取回调函数数组)不然当emit触发事件时会多次触发不同时间阶段的回调函数;所以通过bus.all.get(“myClick”)判断"myClick"事件类型是否存在。import {getCurrentInstance} from "vue"可以获取当前组件实例。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值