Home  >  Q&A  >  body text

Vue 3 - How to use components and mixins in root component?

<p>I tried converting the syntax from Vue 2 to Vue 3 but I'm not sure how to include <em>mixins</em> and <em>components</em> if you see this for Vue 2 Code: </p> <pre class="brush:php;toolbar:false;">import App from "./App.vue"; const app = new Vue({ mixins: [globalMixin], router, el: '#app', store, components: { Thing, Hello }, render: h => h(App) });</pre> <p>This is the syntax for Vue 3, if I understand it correctly: </p> <pre class="brush:php;toolbar:false;">const app = createApp(App) app .use(store) .use(router) app.mount('#app')</pre> <p>The example for Vue 2 has a mixin and two components, but how do I add them to Vue 3's syntax? You can add a component by doing: <code>app.component('Thing', Thing)</code>, but that's just one component... should I add them one by one? What about blending in? </p>
P粉340980243P粉340980243445 days ago602

reply all(2)I'll reply

  • P粉680000555

    P粉6800005552023-08-25 13:31:15

    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 this way because it's clearer.

    reply
    0
  • P粉776412597

    P粉7764125972023-08-25 13:14:46

    In Vue 3, local component registration and mixins are possible in the root component (very useful when trying to avoid polluting the global namespace). Use extendsoptions to extend the component definition of App.vue, 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 components one by one seems like a good approach, especially if there are only a few components.

    Demo

    reply
    0
  • Cancelreply