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.

Smasher
  • 46
  • 7
  • What is the problem with imports? They are supposed to make things more predictable and maintainable – Estus Flask Oct 21 '21 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. – Smasher Oct 22 '21 at 09:49
  • You can likely achieve this by extending a base component, e.g. https://stackoverflow.com/questions/35964116/how-do-i-extend-another-vuejs-component-in-a-single-file-component-es6-vue-loa . But I'd say that the motivation is wrong and isn't worth it. – Estus Flask Oct 22 '21 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. – Estus Flask Oct 22 '21 at 22:20

1 Answers1

0

Have you tried this?

main.js

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


Vue.mixin(yourGlobalMixin)

PawFV
  • 394
  • 2
  • 8
  • 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. – Smasher Oct 21 '21 at 14:40
  • 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](https://www.dropbox.com/s/nbcupdxvylgl2jm/h8F5DMa0QO.mp4?dl=0) – PawFV Oct 21 '21 at 15:02