Reputation: 93
I want to use a global mixin in vue3. Using the mixin property - mixin:[mixinName] in createApp does not work. Using the method .mixin(mixinName) will work. What is the difference?
Not working:
return createApp({
mixins: [utilsMixin],
setup() {
return () => h(HelloWorld, {}, () => childComponents)
}
})
Working Version:
return createApp({
setup() {
return () => h(HelloWorld, {}, () => childComponents)
}
}).mixin(utilsMixin)
Upvotes: 0
Views: 1043
Reputation: 5183
Both variants work. Check the playground below.
But you should be careful by mixing Options API with Composition API.
The mixins
option mixins: [utilsMixin]
is from Options API
and the setup()
function is from Composition API.
Using Options API
together with Composition API
could cause conflicts.
I should also state that using Mixins is deprecated with Vue 3.
No Longer Recommended
In Vue 2, mixins were the primary mechanism for creating reusable chunks of component logic. While mixins continue to be supported in Vue 3, Composition API is now the preferred approach for code reuse between components.
const { createApp, h, onMounted } = Vue
const utilsMixin = {
mounted() {
console.log('utilsMixin.mounted()')
}
}
createApp({
mixins: [utilsMixin],
setup() {
onMounted(() => console.log('app1.onMounted()'))
return () => h('div', {}, 'app1')
}
}).mount('#app1')
createApp({
setup() {
onMounted(() => console.log('app2.onMounted()'))
return () => h('div', {}, 'app2')
}
}).mixin(utilsMixin).mount('#app2')
#app { line-height: 1.75; }
[v-cloak] { display: none; }
label { font-weight: bold; }
<div id="app1" v-cloak>
</div>
<br/>
<div id="app2" v-cloak>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
Upvotes: 0