jason_decode
jason_decode

Reputation: 298

Vue dynamic mapGetters

I have a props that i want to use to make a dynamic mapGetters but the the mapGetters sees the props as undefined, probably because the computed is loaded before the props. Do anybody know how i can make it dynamic? my code is as follow:

export default {
    props: ['listType'],
    components: {
        addrow: AddRow
    },
    computed: {
        ...mapGetters({
            list: `${this.listType}/list`,
            current: 'Dropdown/current'
        }) 
    },
}

Upvotes: 11

Views: 4078

Answers (3)

Eric Norcross
Eric Norcross

Reputation: 4306

What I found that worked was essentially rolling your own mapGetters method in the created() stage of the lifecycle.

Note that this solution has NOT been fully vetted and I have no idea what, if any "gotchas" it may create. As always, caveat emptor.

export default {
  props: ['listType'],
  components: {
    addrow: AddRow
  },
  created() {
    // This can be configured a number of ways, but for brevity:
    const mappableGetters = {
      list: `${this.listType}/list`,
      current: 'Dropdown/current'
    }

    Object.entries(mappableGetters).forEach(([key, value]) => {
      // Dynamically defines a new getter on `this`
      Object.defineProperty(this, key, { get: () => { return this.$store.getters[value] } })
    })

    // Now you can use: `this.list` throughout the component
  },
  computed: {
    // Roll your own mapper above in `created()`
    // ...mapGetters({
    //   list: `${this.listType}/list`,
    //   current: 'Dropdown/current'
    // })
  }
}

Upvotes: 0

samlandfried
samlandfried

Reputation: 821

You can also use this.$store for complete access to the store. So, list would become

export default {
    props: ['listType'],
    computed: {
        list() {
            return this.$store.getters[`${this.listType}/list`]
        }
    }
}

Use the dispatch method to trigger an action, like so

export default {
    props: ['listType'],
    methods: {
        sortList(order) {
            this.$store.dispatch(`${this.listType}/list`, order)
        }
    }
}

Upvotes: 5

jason_decode
jason_decode

Reputation: 298

[UPDATE] I have found the solution thanks to @boussadjrabrahim My working code look like this:

export default {
    props: ['listType'],
    components: {
        addrow: AddRow
    },
    computed: {
        ...mapGetters({
            current: 'Dropdown/current'
        }), 

        ...mapState({
            list (state, getters) {
                return getters[`${this.listType}/list`]
            }
        })
    }
}

Upvotes: 14

Related Questions