Kill code duplication using mixins in Vue

December 24, 2018

When we had the same code in two o more components it is a signal or smells that something is wrong, then the Mixins come to help us.

The mixins allow share data, behavior, and events between components or Vue instances easily, reducing code duplication.

I will give you an example, we had 2 components Remember.vue and Delivery.vue, each one needs to show a range of available days and selected day.

Remember.vue is a list of checkbox options where the user set the frequency of notifications.

The Delivery.vue allow the user to pick when getting the package and contains the same data and behavior.

… something wrong here?

Something wrong… Something wrong…

Create Mixin

Create the file dateRangeMixin.js which export a const containing data properties to be replicated between components, every component had his own copy that means every component can modify his own list without affect other.

export const dateRangeMixin = {
data() {
return {
options: [‘Today’, ‘Tomorrow’, ‘Some Day’],

Using Mixin

Import dateRangeMixin.js into every component which wants to have access and into mixins array set dataRangeMixin.

import { dateRangeMixin} from ”@/dateRangeMixin”;

export default {
name: “Delivery”,
mixins: [dateRangeMixin]

And we can share lifecycle events like created, mounted, unmounted, methods or computed properties.

import { dateRangeMixin } from ”@/dateRangeMixin”;

export default {
name: “Remember”,
mixins: [ dateRangeMixin ]

An important tip if adding some code into our mixin the order execution is the mixin first then the component, our component take the last decision.

There you have it! avoid code duplication using mixins. I hope you enjoyed and hope it saved a few lines of code.

Dany Paredes

Hi, I'm Dany Paredes, few years ago I was working with .NET, but in my last years I have been focusing in Javascript using Vue , Angular or React. You can read more in Twitter or Github.