Sunrise in the fog

    Vue Mixins

    Vue is becoming a more and more popular framework. And it gives us some pretty great ways of keeping code clean and reusable (one of the reasons I love it). One of the ways it does that is through the use of what it has named "mixins".

    What is a mixin? It's reusable code (as you probably know by now), but it isn't just a file you import and run like any old JS file. Mixins allow us to import Vue specific code, like computed properties, and inject it straight into our components. 

    For example, suppose we want the same computed property in several components. We don't want to copy/paste that property, but we also can't just throw it into any JS file. That's what we want mixins for. 

    Let's look at a real example. Say we have a blog, and we want to display some of our top articles in a couple places. Maybe the sidebar, the footer, maybe as tiles on the homepage, etc. Let's say we've got the articles in our Vuex store. We could, when we first get the articles, also store a copy of sorted articles in the store. But we've already got the articles, and then we still need to define our computed property and have it grab the sorted articles from the Vuex store. I would rather keep the store clean, and do less in my components. 

    There's two things we need to do: we need to create our mixin, and then add it to our components. First, let's make our mixin:

    [gist src=https://gist.github.com/benrgreene/028a61bc63140f0999a48b4e95f31d6b file=mixin.js][/gist]

    Now we just need to import it in our component, and then add the import in our component's mixin property.

    [gist src=https://gist.github.com/benrgreene/028a61bc63140f0999a48b4e95f31d6b file=component.vue][/gist]

    Now, everything in the mixin get's loaded in like it's part of the component. Any computed property defined in our mixin's export will be available in our component that loads it. Now we can have DRY code in our Vue components, in a Vue manner! It's one of the easiest & quickest ways to reuse code in our Vue app.