Search code examples
javascriptvue.jsvue-componentvuexcomputed-properties

Replace a computed getter/setter with mapState and mapMutations


So, I am syncing a computed value to a component and setting it with a computed setter when it syncs back from the component.

My question is: Is it possible to replace a computed getter/setter with mapState and mapMutations or how would one achieve this in a more compact way?

<template>
    <SomeComponent :value.sync="globalSuccess"></SomeComponent>
</template>
export default {
    //...
    computed: {
        globalSuccess: {
            get() {
                return this.$store.state.globalSuccess;
            },
            set(val) {
                this.$store.commit("globalSuccess", val);
            }
        }
    }
}

I tried replacing it like this:

export default {
    //...
    computed: {
        ...mapState(["globalSuccess"]),
        ...mapMutations(["globalSuccess"]),
    }
}

But unfortunately mapMutations(["globalSuccess"]) maps this.globalSuccess(value) to this.$store.commit('globalSuccess', value) according to the documentation of vuex.

But since my computed value gets set with globalSuccess = true internally through :value.sync in the template and not this.globalSuccess(true), globalSuccess will never be set to true.

Any idea how this could be possible? Or am I stuck using computed values with getter and setter?


Solution

  • So I just found out about this vuex module https://github.com/maoberlehner/vuex-map-fields which I installed as described on there:

    // store.js
    import { getField, updateField } from 'vuex-map-fields';
    Vue.use(Vuex);
    export default new Vuex.Store({
        getters: {
            getField,
            //...
        },
        mutations: {
            updateField,
            //...
        },
    });
    

    And then I made use of mapFields function:

    // App.vue
    export default {
        //...
        computed: {
            ...mapFields(["globalSuccess"]),
        }
    }
    

    Which apparently dynamically maps to a computed setter and getter exactly as I wanted it:

    export default {
        //...
        computed: {
            globalSuccess: {
                get() {
                    return this.$store.state.globalSuccess;
                },
                set(val) {
                    this.$store.commit("globalSuccess", val);
                }
            }
        }
    }