walox
walox

Reputation: 705

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?

Upvotes: 2

Views: 1641

Answers (2)

Elise Patrikainen
Elise Patrikainen

Reputation: 333

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
}

Upvotes: 1

Cosimo Chellini
Cosimo Chellini

Reputation: 1730

IMHO you should use create 2 things:

  • the plugin that imports the essentials globally
  • the mixin that needs to be imported in the components you want

example:

//main.js
import {MyPlugin} from 'my-library'

vue.use(MyPlugin)

in the component

//component.vue
import {MyMixin} from 'my-library'

export default {
   mixins: [myMixin],
}

Upvotes: 2

Related Questions