Vue.js 3 event bus
P粉905144514
P粉905144514 2023-08-24 18:08:45
0
2
506
<p>How to create an event bus in Vue 3? </p> <hr /> <p>In Vue 2, it is: </p> <pre class="brush:js;toolbar:false;">export const bus = new Vue(); </pre> <pre class="brush:js;toolbar:false;">bus.$on(...) bus.$emit(...) </pre> <hr /> <p>In Vue 3, <code>Vue</code> is no longer a constructor, and <code>Vue.createApp({});</code> returns a without <code>$ on</code> object code> and <code>$emit</code> methods. </p>
P粉905144514
P粉905144514

reply all(2)
P粉638343995

On Vue.js version 3, you can use third-party libraries or functions written in the publisher-subscriber (PubSub concept) programming pattern.

Event.js

//events - a super-basic Javascript (publish subscribe) pattern

class Event{
    constructor(){
        this.events = {};
    }

    on(eventName, fn) {
        this.events[eventName] = this.events[eventName] || [];
        this.events[eventName].push(fn);
    }

    off(eventName, fn) {
        if (this.events[eventName]) {
            for (var i = 0; i < this.events[eventName].length; i++) {
                if (this.events[eventName][i] === fn) {
                    this.events[eventName].splice(i, 1);
                    break;
                }
            };
        }
    }

    trigger(eventName, data) {
        if (this.events[eventName]) {
            this.events[eventName].forEach(function(fn) {
                fn(data);
            });
        }
    }
}

export default new Event();

index.js

import Vue from 'vue';
import $bus from '.../event.js';

const app = Vue.createApp({})
app.config.globalProperties.$bus = $bus;
P粉744831602

As suggested in the official documentation , you can use the mitt library to dispatch events between components, assuming we have a sidebar and header where Contains a button to close/open the sidebar, which we need to toggle certain properties within the sidebar component:

Import the library in main.js and create an instance of the emitter and define it as Global properties:

Install:

npm install --save mitt

usage:

import { createApp } from 'vue'
import App from './App.vue'
import mitt from 'mitt';
const emitter = mitt();
const app = createApp(App);
app.config.globalProperties.emitter = emitter;
app.mount('#app');

Emit a toggle-sidebar event with some payload in the header:

<template>
  <header>
    <button @click="toggleSidebar"/>toggle</button>
  </header>
</template>
<script >
export default { 
  data() {
    return {
      sidebarOpen: true
    };
  },
  methods: {
    toggleSidebar() {
      this.sidebarOpen = !this.sidebarOpen;
      this.emitter.emit("toggle-sidebar", this.sidebarOpen);
    }
  }
};
</script>

Receive events with payload in the sidebar:

<template>
  <aside class="sidebar" :class="{'sidebar--toggled': !isOpen}">
  ....
  </aside>
</template>
<script>
export default {
  name: "sidebar",
  data() {
    return {
      isOpen: true
    };
  },
  mounted() { 
    this.emitter.on("toggle-sidebar", isOpen => {
      this.isOpen = isOpen;
    });
  }
};
</script>

For those using the composition API, they can use emitter as follows:

Create file src/composables/useEmitter.js

import { getCurrentInstance } from 'vue'

export default function useEmitter() {
    const internalInstance = getCurrentInstance(); 
    const emitter = internalInstance.appContext.config.globalProperties.emitter;

    return emitter;
}

From there, you can use useEmitter just like you would use useRouter:

import useEmitter from '@/composables/useEmitter'

export default {
  setup() {
    const emitter = useEmitter()
    ...
  }
  ...
}

Using the Combination API

You can also benefit from the new composition API and define composable event buses:

eventBus.js

import { ref } from "vue";
const bus = ref(new Map());

export default function useEventsBus(){

    function emit(event, ...args) {
        bus.value.set(event, args);
    }

    return {
        emit,
        bus
    }
}

Perform the following operations in component A:

import useEventsBus from './eventBus';
...
//in script setup or inside the setup hook
const {emit}=useEventsBus()
...
 emit('sidebarCollapsed',val)

In component B:

const { bus } = useEventsBus()

watch(()=>bus.value.get('sidebarCollapsed'), (val) => {
  // destruct the parameters
    const [sidebarCollapsedBus] = val ?? []
    sidebarCollapsed.value = sidebarCollapsedBus
})

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template