Kill code duplication using mixins in Vue

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.

<template>
<div class="box">
<h2>Pick delivery day</h2>
<select v-model="selectedOption" >
<option v-for="o in options" :key="o">{{o}}</option>
</select>
<p>{{selectedOption}}</p>
</div>
</template>
<script>
export default {
name: "Delivery",
data() {
return {
options: ['Today', 'Tomorrow', 'Some Day'],
selectedOption:''
}
}
}
</script>

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

<template>
<div class="box">
<h2>Reminder alarm. </h2>
<div v-for="o in options" :key="o">
<label>{{o}}</label>
<input type="radio" v-model="selectedOption" :value="o" />
</div>

<span>{{selectedOption}}</span>
</div>
</template>
<script>
export default {
name: "Remember",
data() {
return {
options: ['Today', 'Tomorrow', 'Some Day'],
selectedOption:''
}
}
}
</script>

… something wrong here?

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'],
selectedOption:''
}
}
}

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.