Emitting Vue.js events in Typescript
Read this article to learn more about how to emit an event in Typescript and listen for it in Vue.js.
Join the DZone community and get the full member experience.
Join For Free
Vue.js allows users to emit an event from a child component and react to it in parent component via this.$emit('event-name') . While this works like a charm when being used directly in components, it does create an issue when working with TypeScript.
Understanding the Issue
Let’s assume (based on my private code) that:
- There is an
UserController.tsclass (on front), which then has a methodinvalidateTokenAndRedirectUser. VueRouterGuard.tsclass which handles theonRouteChangelogic, and this is where the invalidation happens.
Now the user won’t do anything for like 1 hour and eventually, the token will be invalidated. The VueRouterGuard checks in place (before going to the next route) if the token has expired.
If the user gets invalidated, I suggest:
- Move user to
loginpage. - Hide the
logoutmenu element. This is the problem, as the nav is controlled by Vue.js and DOM should NOT be manipulated directly for that purpose.
With this solution where VueRouterGuard invalidates the user, none of the Vue.js components/Views ever receives information that something happened.
Emitting Event From Typescript
By checking the source code of Vue.js to better understand how the events emitting works, I’ve found this:

And this looks just like the standard Event from Js.
So I’ve personally come up with this solution:
/**
* @description this service handles dispatching events,
* can also be used to dispatch events from within TS onto the VUE elements
* (this is not recommended for small components etc but can work just fine when used on router-view)
*/
export default class EventDispatcherService
{
static readonly EVENT_NAME_USER_INVALIDATED = "user-invalidated";
private static readonly ROUTER_VIEW_DOM_ID = "routerView"
/**
* @description will dispatch the event directly on vue `router-view`
*/
public static emitEventOnRouterView(eventName: string): void
{
let event = new Event(eventName);
let routerViewDomElement = document.getElementById(this.ROUTER_VIEW_DOM_ID);
if(null === routerViewDomElement){
let message = "Vue `router-view` was not found in DOM for id: " + this.ROUTER_VIEW_DOM_ID;
Logger.error(message);
throw new BaseError(message);
}
routerViewDomElement.dispatchEvent(event);
}
}
The emitEventOnRouterView method will take a RouterView DOM element and emit an event on it. And with that, the provided event can be listened to just like standard $emit('name').
<template>
<router-view
id="routerView"
@login-success="handleLoginSuccess()"
@user-invalidated="handleUserInvalidated()"
/>
</template>
Published at DZone with permission of Dariusz Włodarczyk. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments