Vue 3 Emits

Posted on  by admin

Vue 3 has made some slight changes to how Vue components work. The basic syntax for creating Vue components hasn't changed much, but there's a lotof new features for you to take advantage of.

Here's an overview of how components have changedin Vue 3. If you drop Vue 3 into an existing Vue 2 codebase, odds are the first error you'll see is TypeError: Vue is not a constructor.

That's because the Vue global is now no longer a class. Instead of usingnew Vue() to create a new app, you should use Vue.createApp().

And, instead of registeringcomponents globally using Vue.component(), you register components on apps using app.component().

For example, below is a component in Vue 2:. Below is how you would rewrite it for Vue 3:. There are 4 necessary changes:.

Use createApp() instead of new Vue(). Use app.component() instead of Vue.component().

Switch the order of definition, so you define the app before the component. Use mount() instead of $mount().

  • The basics still work: you still define props the same way, and you can still $emit() eventsfrom your component.
  • The only difference is that you now need to explicitly define what events yourcomponent emits like how you explicitly define a list of props.
  • Below is an example of how you can use $emit() with Vue 2:.

Below is how you would change the above example to work with Vue 3. Besides the usual createApp()and app.component() changes, this example also adds a list of events the component emits.

đź”—