Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
        }) 
    },
}
like image 958
jason_decode Avatar asked Sep 30 '18 12:09

jason_decode


2 Answers

[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`]
            }
        })
    }
}
like image 144
jason_decode Avatar answered Sep 27 '22 23:09

jason_decode


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)
        }
    }
}
like image 40
samlandfried Avatar answered Sep 27 '22 23:09

samlandfried