Search code examples
javascriptvue.jsvue-componentes6-class

Should I use mixins or an utility class?


I have a Vue.js project that use one method in multiple files, so I create an utility class to write this method there, something like:

export class Util{
  doSomething(){
    return 'something'
  }
}

But I know that I can do it using mixins, like:

export const myMixin = {
   methods: {
     doSomething(){
       return 'something'
     }
   }
}

Should I use mixin or an utility class?

When should I use one of them?


Solution

  • This is a great question. Unfortunately, there is no precise answer but I'll provide some guidelines based on my own experience working with a large Vue codebase.

    Mixins

    Mixins are ideal for situations where you have a collection of interdependent non-side-effect-free code that you'd like to share between components.

    In my case, I have an input mixin that defines props, some data (unique ids for input and error elements), and methods for emitting events like blur. It's ~60 lines of code, that I'd otherwise have to retype for each of nine different components.

    The benefits of a mixin are similar to that of an inherited class in traditional OOP. I.e. code reuse and complexity encapsulation.

    The primary disadvantage of a mixin, is that it can make your code harder to read. Imagine you come back to work on the AppTextArea component six months later, and it isn't obvious how and why certain things work or where they are defined... then you remember it uses a mixin, and then you have to dive into the mixin code... In other words it makes for implicit, rather than explicit implementations.

    Shared Functions

    Shared functions are ideal for situations where you can reuse units of side-effect-free code in your application.

    In my case, I have a date library with a formatBySlash function which takes a Date object and returns something like "5/12/2018". I've added it as a global filter, so I can do things like {{ post.createdAt | formatBySlash }} in my templates. Additionally I can import the function and use it directly in a method or computed property.

    Shared functions are flexible, easy to test, and make your code more explicit.


    In summary, I'd generally recommend writing a shared function unless your use case really requires that it be a mixin.