DEV Community

loading...

vue-typed-emit

3vilarthas profile image Andrew ・1 min read

Introduction

A half a year has already passed since I wrote the Vue.js Typed events article. During all this time I was searching for a solution, which doesn't require from a developer to change the way how one is used to emit events in Vue.js components (this.$emit('event', payload)). Finally I've found one, and that's resulted in vue-typed-emit library creation.

Features

The main feature of the library is that it doesn't require from a developer any typed wrappers over a this.$emit invocation. It only requires a simple type which describes names of events your component is supposed to emit along with corresponding payloads.

Here is a trivial example:

import Vue from 'vue'
import { WithEvents } from 'vue-typed-emit'

interface Events {
  foo: string
  bar: [string, number]
  baz: undefined
}

export default (Vue as WithEvents<Events>).extend({
  name: 'Component',
  methods: {
    method() {
      this.$emit('foo', 'foo')
      this.$emit('bar', 0)
      this.$emit('baz')
    },
  },
})

vue-typed-emit verifies that component emits only declared events with valid payloads.

If a developer tries to emit invalid event or invalid payload, one gets an error from TypeScript.

TypeScript error

TypeScript error

You can find vue-type-refs on GitHub and NPM. Feel free to contribute.

Discussion

pic
Editor guide
Collapse
romalyt profile image
Roman

Hey! Thanks for the article, nice solution.

What do you think about new emits property? It allows you to type hint emits when using with TS. For example:

export default defineComponent({
  emits: {
    'foo': (arg: string) => { // some validation logic for runtime },
  },
  mounted () {
    tis.$emit('foo', 1) // type error, you can emit only strings for 'foo' event
  },
})
Enter fullscreen mode Exit fullscreen mode

Further reading:
v3.vuejs.org/api/options-data.html...
github.com/vuejs/rfcs/blob/master/...