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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • React, Angular, and Vue.js: What’s the Technical Difference?
  • Leveraging Salesforce Using a Client Written In Vue.js
  • Streamlining Event Data in Event-Driven Ansible
  • Beyond Linguistics: Real-Time Domain Event Mapping with WebSocket and Spring Boot

Trending

  • Start Coding With Google Cloud Workstations
  • Is Agile Right for Every Project? When To Use It and When To Avoid It
  • Automating Data Pipelines: Generating PySpark and SQL Jobs With LLMs in Cloudera
  • The Human Side of Logs: What Unstructured Data Is Trying to Tell You
  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 user avatar
Dariusz Włodarczyk
·
Aug. 25, 21 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
4.9K Views

Join the DZone community and get the full member experience.

Join For Free

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
  • Streamlining Event Data in Event-Driven Ansible
  • Beyond Linguistics: Real-Time Domain Event Mapping with WebSocket and Spring Boot

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!