How to use global mixins in nuxt 3
Trevash opened this issue · 2 comments
Hey I'm trying to import and add a global mixin file to be used on all pages, but the technique I used in Nuxt 2 doesn't seem to be available in Nuxt 3. The reason I want to add a global mixin file is so that I have access to functions I'll use on almost every page without having to import the mixin each time.
Here is what I have done in the past in either my app.vue file or my layouts/default.vue file depending on my file structure:
import Vue from 'vue'
import globalMixin from '~/mixins/globalMixin.js'
Vue.mixin(globalMixin)
When I attempt to do this in Nuxt 3, I get the error 'Cannot read property mixin of undefined'.
After some experimentation I was able to change my import so that it worked with es6 by doing import * as Vue from 'vue'
. This solved the issue above, but when I tried to do the same command above Vue.mixin(globalMixin)
I got a new error 'vite_ssr_import_0.mixin is not a function'. Can anybody help me add a global mixin or is there another more effective way to make a group of functions available globally?
If you want to use a global mixin, you should register it in a plugin (no matter if you use Nuxt2 or Nuxt3 😋) and not in the layout.
The global Vue.use
API does not exist in Vue 3 anymore. Instead, you have to get the app
somehow and call use
there.
Here is an examplary Nuxt plugin that will apply the global mixin as you desired.
import globalMixin from '~/mixins/globalMixin.js'
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.vueApp.use(globalMixin)
})
Awesome, thank you!