Search code examples
javascriptvue.jsvuejs2vue-componentvue-mixin

Vuejs : use imported plugin mixin localy


Is it possible to use a mixin imported from a VueJS plugin in one component?

I've created a plugin and when I import it I can access the mixin's functions from all my components.

Is there a way to make it available in only one component ? or all the plugin add global-level functionality to Vue by definition?


Solution

  • You can register a mixin either globally, either locally. If you don't register a mixin globally, it will be only available in components where it is locally registered. So, with local registration, you can make a mixin available in only specific components.

    Registering globally: you just need to declare it in the main.js file
    Nb: you don't need to register the mixin in components

    • Vue 2:
    // main.js
    import myMixin from './mixins/myMixin'
    
    Vue.mixin(myMixin)     // makes the plugin globally available 
    new Vue({
       // ...
    }).$mount('#app')
    
    
    • Vue 3:
    // main.js
    import myMixin from './mixins/myMixin'
    
    const app = createApp(App)
    app.mixin(myMixin)     // makes the plugin globally available 
    app.mount('#app')
    

    Registering locally: you do NOT declare it in the main.js file, and you register the mixin in the relevant components

    // componentWithMixin.vue
    import myMixins from "../mixins/myMixin"
    
    export default {
        // ...
        mixins: [myMixins]     // importing the mixin - without this line, the mixin can't be available
    }