Search code examples
javascriptvue.jsvuejs2vuexvuex-modules

pass prop value to computed properties inside a component


Is it possible/good practice to use a prop value inside a computed property function inside a component? If so, how do I build the return with this prop?

Carousel.vue

props: [
  'source',
],
computed: {
   items () {
     return this.$store.state.(prop value source here).list
   }
}

store/categorya.js (the same for categoryb and categoryc)

import categorya from '(...)'
export const state = () => ({
  list: categorya
})

Update

Index.vue

carousel(source="categorya")
carousel(source="categoryb")
carousel(source="categoryc")

Solution

  • The question is a bit unclear. If source specifies a Vuex module name you could use bracket notation:

    computed: {
      items () {
        return this.$store.state[this.source].list
      }
    }
    

    AFTER YOUR EDIT

    Still unclear, but if there are no modules and list is a property of root state, then you would simply use:

    computed: {
      items () {
        return this.$store.state.list
      }
    }
    

    The fact that list is first defined by an import called categorya makes no difference. It's still the only state available and its name is just list.