DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • React, Angular, and Vue.js: What’s the Technical Difference?
  • Leveraging Salesforce Using a Client Written In Vue.js
  • When Feature Flags Become Workflows: Configuring Multi-Tenant State Machines
  • Java to TypeScript in a Day: AI Migration Playbook

Trending

  • Choosing Voice AI Infrastructure: 7 Capabilities To Evaluate
  • Introduction to Error Prone: How to Catch Bugs at Compile Time
  • "Works on My Machine" Is an Architecture Problem
  • From Issue to Reviewable Patch: Build a Sandboxed Coding Agent With Deep Agents and Automated Tests

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. JavaScript
  4. Emitting Vue.js events in Typescript

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.

By 
Dariusz Włodarczyk
·
Aug. 25, 21 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
5.3K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Vue.js + Type Script logos

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.ts class (on front), which then has a method invalidateTokenAndRedirectUser.
  • VueRouterGuard.ts class which handles the onRouteChange logic, 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 login page.
  • Hide the logout menu 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:

Emitting in Vue.js

And this looks just like the standard Event from Js.

So I’ve personally come up with this solution:

TypeScript
 
/** 
 * @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').

Vue.js Component
 
<template>
  <router-view
      id="routerView"
      @login-success="handleLoginSuccess()"
      @user-invalidated="handleUserInvalidated()"
  />
</template>


Vue.js Event TypeScript

Published at DZone with permission of Dariusz Włodarczyk. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • React, Angular, and Vue.js: What’s the Technical Difference?
  • Leveraging Salesforce Using a Client Written In Vue.js
  • When Feature Flags Become Workflows: Configuring Multi-Tenant State Machines
  • Java to TypeScript in a Day: AI Migration Playbook

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook