MiBunZhu
MiBunZhu

Reputation: 31

Conventional Vue structure for similar functionalities components (with Vuex)

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() {...},
  },
}

Upvotes: 2

Views: 61

Answers (1)

MiBunZhu
MiBunZhu

Reputation: 31

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() {...},
  },
}

Upvotes: 1

Related Questions