1

I want to use a mixin in multiple components without having to write an import and use declaration every time. I already tried connecting the mixin object to a global variable via vue.prototype but mixins get added to components before globals are even accessible. Also i cannot import the mixin globally without also adding it to all components globally (which i don't want). If anyone has a suitable solution that does not include much code i would appreciate it. As this is my 1st question on here feel free to leave suggestions for improvement.

Edit: I'm fine with globally importing the mixin but I want to define myself which components use the mixin.

Edit 2: Another Solution would be an inline import inside the mixins array but i didn't find a way to do it. Neither with require() nor import().

Edit 3: I decided to stick with using the mixin locally.

4
  • What is the problem with imports? They are supposed to make things more predictable and maintainable Commented Oct 21, 2021 at 15:25
  • I would like to keep code duplication to a minimum. Having to write the same 2 lines in every component that uses the mixin is not very helpful. If i have the option to do that with just one line it would be optimal. Commented Oct 22, 2021 at 9:49
  • You can likely achieve this by extending a base component, e.g. stackoverflow.com/questions/35964116/… . But I'd say that the motivation is wrong and isn't worth it. Commented Oct 22, 2021 at 22:18
  • Let's say you need to provide components with a subset of functionality, i.e. make them Cars. And then it appears that they need to be provided with a different sort of functionality and be also Apples. Multiple inheritance is a common design issue with OOP and else. The solution is to use mixin pattern, with OOP, or Vue, or whatever. This is the reason why mixins exist in Vue. They provide a clean way to extend the functionality of components and not limit it to parent-child relationship. Commented Oct 22, 2021 at 22:20

1 Answer 1

0

Have you tried this?

main.js

import yourGlobalMixin from '@/mixins/yourGlobalMixin.js'


Vue.mixin(yourGlobalMixin)

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, this is exactly what i don't want because now all components will use the Mixin. For clarification: I'm fine with globally importing but want to define myself which components use the mixin.
Yep if that's not what you want then you have to import them in each component that you want to use it. Anyways it's not really time consuming if you use the auto-import feature of your editor

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.