vue2与vue3的全局通信插件,如何实现自定义的插件

Vue 2 自定义插件(事件总线实现)

在 Vue 2 中,可以通过事件总线来实现全局通信。以下是创建一个简单事件总线插件的步骤:

  1. 创建插件文件 eventBus.js

    // eventBus.js
    import Vue from 'vue';

    const EventBus = new Vue();

    export default {
    install(Vue) {
    Vue.prototype.$bus = EventBus; // 将 EventBus 添加到 Vue 原型上
    },
    };

2.在主文件中引入插件并使用

复制代码
// main.js
import Vue from 'vue';
import App from './App.vue';
import EventBus from './eventBus';

Vue.use(EventBus);

new Vue({
  render: (h) => h(App),
}).$mount('#app');

3.在组件中使用

  • 触发事件

    this.bus.emit('my-event', { data: 'Hello, World!' });

监听事件

复制代码
this.$bus.$on('my-event', (payload) => {
  console.log(payload.data);
});

Vue 3 自定义插件(使用 provideinject 实现)

在 Vue 3 中推荐使用 provideinject API 来进行全局通信,可以实现更灵活的插件结构。

  1. 创建插件文件 eventBus.js

    // eventBus.js
    import { reactive } from 'vue';

    const EventBus = reactive({
    events: {},

    on(event, callback) {
    if (!this.events[event]) {
    this.events[event] = [];
    }
    this.events[event].push(callback);
    },

    off(event, callback) {
    if (!this.events[event]) return;
    this.events[event] = this.events[event].filter(cb => cb !== callback);
    },

    emit(event, payload) {
    if (!this.events[event]) return;
    this.events[event].forEach(callback => callback(payload));
    },
    });

    export default {
    install(app) {
    app.provide('eventBus', EventBus);
    },
    };

2.在主文件中引入插件并使用

复制代码
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import EventBus from './eventBus';

const app = createApp(App);
app.use(EventBus);
app.mount('#app');

3.在组件中使用

  • 触发事件:

复制代码
  import { inject } from 'vue';

  setup() {
    const eventBus = inject('eventBus');
    
    function triggerEvent() {
      eventBus.emit('my-event', { data: 'Hello, World!' });
    }

    return { triggerEvent };
  }

监听事件:

复制代码
import { inject, onMounted, onUnmounted } from 'vue';

setup() {
  const eventBus = inject('eventBus');

  function handleEvent(payload) {
    console.log(payload.data);
  }

  onMounted(() => {
    eventBus.on('my-event', handleEvent);
  });

  onUnmounted(() => {
    eventBus.off('my-event', handleEvent);
  });
}
相关推荐
_zhourui_h_几秒前
一个 [ECS] 到底生成了多少代码?EasyECS 最核心的秘密都在这里
前端
梨想橙汁2 分钟前
Git 分支详解:创建切换、合并分支、冲突解决实战
前端·git
雪芽蓝域zzs4 分钟前
Vue3 defineProps` / `defineEmits` 是编译器宏,不需要手动 import 导入
前端·javascript·vue.js
whyweplay8 分钟前
Elpis:从Json Schema 到 页面
前端·javascript
大牧师42 分钟前
Nest.js 微服务入门教程
开发语言·javascript·后端·微服务·node.js·nest.js·nest
做萤石二次开发的哈哈1 小时前
海康班班通交互一体机技能接入实战:ISAPI透传+OTAP双协议封装,Web/App/小程序教学管理应用一站生成
前端·物联网·小程序·交互·萤石开放平台·蓝海aiot一站式工作台·aiot开发
计算机魔术师1 小时前
Anthropic一次性锁死十年算力,5170亿美元买什么
前端
IT_陈寒1 小时前
Redis的订阅丢失消息?你可能忘了这个配置
前端·人工智能·后端
头茬韭菜1 小时前
第 3 篇:「Pydantic 即 Schema」—— 工具生态三层解剖
前端·chrome·ai·openmanus
低代码布道师1 小时前
外包项目管理平台全栈实战课02搭建数据底座:Next.js + PostgreSQL + Prisma 7
开发语言·javascript·postgresql·全栈开发