tamanakid
tamanakid

Reputation: 843

Vue: Is it an antipattern for a mixin to call a method to be implemented in a component?

I'm currently trying to refactor existing components to be DRY, so I'm building a mixin among other things.

However, I find it necessary to call component's specific methods from within the mixin's own methods or lifecycle hooks and, despite it works, it rings somewhat as an antipattern:

calendarMixin.js:

let calendarMixin = {
  created () {
    this.getCalendar();
  }
};

CalendarOne.vue

export default {
  mixins: [calendarMixin],
  methods: {
    ...mapActions('storeCalendarOne', ['getCalendar'])
  }
};

CalendarTwo.vue

export default {
  mixins: [calendarMixin],
  methods: {
    ...mapActions('storeCalendarTwo', ['getCalendar'])
  }
};

Maybe some sort of documentation in the mixin would be appropiate to specify which methods must be implemented in the component using the mixin, but it doesn't solve any problems regarding the code like an OOP's interface would.

I was also wondering if TypeScript in Vue would provide a solution to this, like defining strict implementation statements in the mixins.

Thanks in advance.

Upvotes: 1

Views: 518

Answers (1)

Tim Wickstrom
Tim Wickstrom

Reputation: 5701

If you are using vuex I would structure my code like this:

/src
  /mixins
    CalendarMixins.js
  /components
    CalendarOne.vue

CalendarMixins.js

import {mapActions} from 'vuex'

export default {
  created () {
    this.getCalendar();
  },
  methods: {
    ...mapActions(['getCalendar'])
  }
}

CalendarOne.vue

import CalendarMixins from '@/mixins/CalendarMixins'
import {mapActions} from 'vuex'

export default {
  mixins: [CalendarMixins],
  methods: {
    ...mapActions('storeCalendarOne')
  }
}

Upvotes: 1

Related Questions