vue.jsvuejs2mixinsvue-mixin

Is it recommended to extract methods of a Vue component which are used by only one component to a Vue mixin?


I am wondering about the best practice on the usage of Vue Mixins: I have a complex Vue component which implements a table with extensive functionality (e.g. sorting, filters). I would like to extract specific functionality such as sorting to a Mixin (for this example methods and a few helper functions) to a separate file.

Is it fine to use the code of a Vue mixin in only one component?

All use cases which are given by example tutorials I only saw Mixins in either of the following two use cases:


Solution

  • I would consider writing an ES module that contains the functions, and importing those instead of a mixin. You can then import these functions into any other component eventually.

    Of course, if it's common functionality to all of them such as adding computed properties etc. then you could write a mixin that imports the original ES module of functions.

    There's probably no point right now making a mixin if nothing else uses it, but I would definitely have an ES module containing that complex logic you mentioned. It would be easier to unit test them too.