Global Components
Registering global components with the app instance
Then, in Vue 2
In our App, we register a Modal
Component globally, so we can use it anywhere in our app without importing it in each of these places. the code relevant looks like this:
import Modal from './components/Modal.vue'
// omitted ...
Vue.component('Modal', Modal)
// recommended
const app = new Vue({ /* omitted */})
Now, in Vue 3
By now you likely have caught on that we now have to register components on the app
instance again, and you're right!
import Modal from './components/Modal.vue'
// omitted ...
Vue.component('Modal', Modal)
const app = createApp(/* omitte */)
app.component('Modal', Modal)
That's all that's required to migrate this part of your app, so we're done!
Tip: handling many components
Maybe you have a bunch of global components, and instead of importing them all into main.js
, you extracted that logic into a components.js
file, something like this:
import Vue from 'vue'
import Component1 from './components/component1.vue'
import Component2 from './components/component2.vue'
// ...
Vue.component('Component1', Component1)
Vue.component('Component2', Component2)
//...
import Vue from 'vue'
import './components'
If you did that, good! That's clean. In Vue 3, as we don't have Vue
anymore, how do we "get app
into that file"?
The solution is basically to turn it into a small plugin, like this:
import Vue from 'vue'
import Component1 from './components/component1.vue'
import Component2 from './components/component2.vue'
// ...
export default function addComponents (app) {
app.component('Component1', Component1)
app.component('Component2', Component2)
// ...
}
import Vue from 'vue'
import addComponents from './components'
// ... ommitted
const app = createApp(/* omitted */)
app.use(addComponents)
This pattern will provide useful in the next two chapters as well, so read on.