How to create multiple mixins in one file and using specific mixins in vue js

2 min read
Mustafa Dalga
Sep 30, 2021

When we have features such as method, computed or watch, that we want to use in more than one component or view, we can create and use mixins to avoid repetitive codes.

In small projects, we can create and import a mixin file for each repetitive feature (method, computed, watch,etc...) and use it. However, as the project grows, creating a mixin file for each feature will cause the mixins folder to swell. Instead of creating many mixin files, we can create a main mixin file per category. It would be a better method to create mixin files according to the scope, collect the mixins in the relevant files, and import only the necessary mixin.

Mixins

We gathered computed and methods that we use in more than one component/view related to insights under mixins/insights/index.js.


import { mapGetters } from "vuex";

const insightsName = {
computed: {
...mapGetters('insights', [ 'getInsightResults' ]),

insightsNames() {
return this.getInsightResults.map(insight => insight.name);
},
}
}

const insightsByType = {
computed: {
...mapGetters('insights', [ 'getInsightResults' ]),
methods: {
insightsByType(type) {
return this.getInsightResults.filter(insight => insight.type == type);
},
}
}
}

const hasInsight = {
computed: {
...mapGetters('insights', [ 'getInsightResults' ]),
methods: {
hasInsight(id) {
return this.getInsightResults.find(insight => insight.id == id);
},
}
}
}

const priorityCountByType = {
computed: {
...mapGetters('insights', [ 'getInsightResults' ]),
methods: {
priorityCountByType(type) {
return this.getInsightResults.filter(insight => insight.priority == type).length;
},
}
}
}

export {
insightsName,
insightsByType,
hasInsight,
priorityCountByType
}

We have included only the mixins we want to use as follows.

import of specific mix

Example usage in template:

<div>Urgent count:{{ priorityCountByType('urgent') }}</div>

Example usage in script:

this.priorityCountByType('urgent')

At the time of writing this article, we used mixins as the best practice. However, we can improve or change solutions over time.

Latest

From the blog

The latest industry news, interviews, technologies, and resources.
No items found.

Get Top landing pages by session

You don't need worry about performance changes or missing opportunities, in one email, heybooster Google Analytics Weekly Report summarizes all.