2

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?

2
  • Simply put: Sure, it is. Just register that mixin within a specific component and you're good to go. Commented Nov 5, 2020 at 10:09
  • Didn't work, even if I register it in one component it became available to all the others. Commented Nov 5, 2020 at 10:11

2 Answers 2

2

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],
}
Sign up to request clarification or add additional context in comments.

Comments

1

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.