Vue 3 - How to use components and mixins in root component?
P粉340980243
P粉340980243 2023-08-24 16:25:32
0
2
540
<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粉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). 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

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!