Emitting Vue.js events in Typescript
How to emit an event in Typescript and listen for it in Vue.js
Vue.js allows users to emit
and 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 i does create an issue when working with TypeScript.
Understanding the issue
Let’s assume (based on my private code) that
- there is an
UserController.ts
class (on front), which then has a methodinvalidateTokenAndRedirectUser
VueRouterGuard.ts
class which handles theonRouteChange
logic and this is where the invalidation happens,
Now — user won’t do anything for like 1 hour and eventually the token will be invalidated. The VueRouterGuard
checks in place (before going to next route) if the the token has expired.
Now if the user get’s invalidated I want to:
- move user to
login
page, - hide the
logout
menu element — and 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 came up with this solution:
The emitEventOnRouterView
method will take a RouterView
DOM element and emit
and event on it. And with that, provided event can be listened just like standard $emit('name')