How to use mixin in VueJS typescript?

Angel iT
2 min readAug 10, 2019

--

It’ve been long time from my last blog post :)

In a couple of months that I was so busy to work with my team for building our product. My exp may not good for a TA position in other company but as a TA in my team, I need to work in deep with code structure, find some best practices of code to help improve our product & also help my members improve their skills. It’s a good time to review Asp.Net Boilerplate again — This is a boilerplate has suggested by my team leader in old company.

.NET Framework + Angular — This story for 2 years ago. Nowaday, it is a time of .NET core & Vúe….oops, sorry, it's VueJS.

ABP using typescript for VueJS, beside that, they also implement some of decorators helpers for improve coding process & the code can more readable.

Seems it’s to much text for my post… Let's take a look into code

Define a mixin

// list-mixin.ts
import { Component } from 'vue-property-decorator';
import AbpBase from '@/lib/abpbase';

@Component
export default class ListMixin extends AbpBase {
namespace: string = 'product';

get store() {
return null;
}
get loading() {
return this.store.loading;
}
}

And in product.vue file we can use this mixin

// product.vue
import ListMixin from '@/components/list-mixin';
import { mixins } from 'vue-class-component';

@Component
export default class Product extends mixins(ListMixin){
namespace = 'product';
get store () {
return this.$store.state.product;
}
}

Oops…wait, This is just a first version of my mixin implementation, The previous version of product.vue was based on AbpBase so it also need to inheritance from it again.

In vue decoration document, I saw that we can pass multiple mixins into mixins helper function, so now we can use AbpBase as a mixin :))

And then the final code is

// product.vue
import ListMixin from '@/components/list-mixin';
import { mixins } from 'vue-class-component';
import AbpBase from '@/lib/abpbase';
@Component
export default class Product extends mixins(AbpBase, ListMixin){
namespace = 'product';
get store () {
return this.$store.state.product;
}
}

With a simple approach using mixin for list component, I can save 50 lines of duplicate code, I want to reduce more lines of duplicate code in the future so I hope we can meet again this my next post.

Thank you all you guys!

--

--