Vue 3 - How to use components and mixins in root component?
P粉340980243
P粉340980243 2023-08-24 16:25:32
0
2
523

I tried converting the syntax from Vue 2 to Vue 3 but I'm not sure how to include mixins and components if you see this for Vue 2 Code:

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

This is the syntax for Vue 3, if I understand it correctly:

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

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: app.component('Thing', Thing), but that's just one component... should I add them one by one? What about blending in?

P粉340980243
P粉340980243

reply all (2)
P粉680000555

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.

    P粉776412597

    In Vue 3, local component registration and mixins are possible in the root component (very useful when trying to avoid polluting the global namespace). Useextendsoptionsto extend the component definition ofApp.vue, then add your ownmixinsandcomponentsoptions :

    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

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!