Vue 3 - how to include components and mixins with the root component?

Viewed 8671

I try to convert the syntax from Vue 2 to Vue 3, but I'm not sure how to include the mixins and components, if you see this code from Vue 2:

import App from "./App.vue";

const app = new Vue({
  mixins: [globalMixin],
  router,
  el: '#app', 
  store,
  components: {
     Thing,
       Hello
  }, 
  render: h => h(App)
});

Here is the Vue 3 syntax, if I've understood it right:

const app = createApp(App)
app 
.use(store)
.use(router) 
 
app.mount('#app')

The vue 2 example has a mixin and two components, but how do I add that to the Vue 3 syntax? You can add a component by doing : app.component('Thing', Thing) but that's only one component...should I add them one by one in that way? What about the mixins?

3 Answers

In Vue 3, it's possible to do local component registration and mixins in the root component (useful when trying to avoid polluting the global namespace). Use the extends option to extend the component definition of App.vue, and then add your own mixins and components options:

import { createApp } from 'vue'
import App from './App.vue'
import Hello from './components/Hello.vue'
import Thing from './components/Thing.vue'
import globalMixin from './globalMixin'

createApp({
  extends: App,
  mixins: [globalMixin],
  components: {
    Hello,
    Thing,
  }
}).mount('#app')

Registering the component one at a time seems like the way to go, especially if there are only a few components.

demo

In Vue 3, you can use the application API mixin method.

import { createApp } from 'vue'
import App from './App.vue'
import globalMixin from './globalMixin'

const app = createApp(App)

app.mixin(globalMixin)

app.mount('#app')

For components, you can add them one by one. I prefer it this way because it is cleaner.

you are right i just tried with your syntax and i deleted the useless import .... but i did not put the mixins in the brackets i did like this :

createApp({ extends: App, mixins: [], beforeCreate() { this.$commerce = commerce; }, }).use(store).use(router).mount('#app')

is right ?

Related