Conventional Vue structure for similar functionalities components (with Vuex)

Viewed 39

Question about conventions on components with similar functionalities but only the getters and actions are different.

How to keep the clean/maintainable while only the getters and actions are different?
Do I use mixin? Higher order component? Use switch cases? And explain you choice if possible

For instance, the following components are:

  1. sharing the same sameFunction1() and sameFunction2()
  2. the only difference is that the getters and actions are different

Component 1

export default {
  // ...
  computed: {
    ...mapGetters([
      'getDog1',
      'getCat1',
    ])
  },
  methods: {
    ...mapActions([
      'setDog1',
      'setCat1',
    ])
    sameFunction1() {...},
    sameFunction2() {...},
  },
}

Component 2

export default {
  // ...
  computed: {
    ...mapGetters([
      'getDog2',
      'getCat2',
    ])
  },
  methods: {
    ...mapActions([
      'setDog2',
      'setCat2',
    ]),
    sameFunction1() {...},
    sameFunction2() {...},
  },
}
1 Answers

Based on Estus Flask comment

We can use mixins and structure the component like abstract classes

Mixin

// define a mixin object
var myMixin = {
  methods: {
    sameFunction1() {...},
    sameFunction2() {...},
  }
}

Component 1

export default {
  mixins: [myMixin],
  // ...
  computed: {
    ...mapGetters([
      'getDog1',
      'getCat1',
    ])
  },
  methods: {
    ...mapActions([
      'setDog1',
      'setCat1',
    ])
  },
}

Component 2

export default {
  mixins: [myMixin],
  // ...
  computed: {
    ...mapGetters([
      'getDog2',
      'getCat2',
    ])
  },
  methods: {
    ...mapActions([
      'setDog2',
      'setCat2',
    ]),
    sameFunction1() {...},
    sameFunction2() {...},
  },
}
Related