DEV Community

Jake Dohm
Jake Dohm

Posted on

Registering Global Components with Vue 3

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!

Top comments (4)

Collapse
 
jackzhoumine profile image
jackzhoumine

Can i do this way?
in index.js

import WatchTest from './WatchTest.vue'
const components = [WatchTest]
export default {
    install(Vue) {
        components.forEach((component) => {
            Vue.use(component.name, component)
        })
    },
}
Enter fullscreen mode Exit fullscreen mode

in main.js

import components from './components'
const vue = createApp(App)
vue.use(components)
Enter fullscreen mode Exit fullscreen mode

it does not work? how to register global component using install?

Collapse
 
melaniecarr23 profile image
Melanie

Thanks! This is super helpful. I'm taking a course on Vue and am converting my site from Vue 2 to 3. I also had to change the way I do filters, and attach moment but it's looking good!

Collapse
 
gormonn profile image
Dmitriy Aleksandrovich

Tnx a lot!

Collapse
 
omarhegazi94 profile image
OMAR HEGAZI

Uncaught TypeError: app.component is not a function