loading...

Registering Global Components with Vue 3

jakedohm_34 profile image Jake Dohm ・2 min read

Vue 3 is now in beta (learn more) so I decided to test it out (using vue-next), and one of the things I had to tweak in my current application is how I was registering my "global" components.

I'll talk about why these changes are necessary below, but if you're just here for the meat of the post, the examples really speak for themselves so here are the actual code changes:

Before

import Vue from 'vue'
import Header from './components/Button.vue'
import App from './App.vue'

// Register Button component globally
Vue.component('Button', Button)

// Create and mount Vue instance
new Vue({
  render: h => h(App)
}).$mount('#app')

After

import { createApp } from 'vue'
import Header from './components/Button.vue'
import App from './App.vue'

// Create Vue instance
const app = createApp(App)

// Register Button component globally
app.component('Button', Button)

// Mount Vue instance
app.mount('#app')

Why are these changes necessary?

Hey, you ask great questions!! Vue 3 changed the way "instances" of Vue work so that they could make the Vue prototype immutable. So now you customize an "instance" of Vue (created with createApp) instead of directly changing the Vue prototype. I'm not sure exactly why this change was made, but that's how things work in Vue 3.

This also means if you're running an app that has multiple Vue instances that share configuration, you'll now need to either 1) duplicate some code or 2) create your own abstraction to share configuration. I'll write more about this soon!

Wrapping up

If you have any questions about this, or any Vue 3 changes, drop me a comment or find me on Twitter @jakedohm . I plan on writing more about Vue 3, so let me know what you'd like me to cover!

Posted on by:

Discussion

markdown guide