P粉6383439952023-08-25 16:53:26
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粉7448316022023-08-25 00:55:58
As suggested in the official documentation , you can use the mitt library to dispatch events between components, assuming we have a sidebar and header< /code> 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 })