Setter for computed property obtained from store in vue.js Setter for computed property obtained from store in vue.js vue.js vue.js

Setter for computed property obtained from store in vue.js


To change Vuex state, you will need a mutation.

Provided you have a mutation setNotification for changing the notification state, you can configure the property in your component like this:

computed: {    notification: {        get() { return this.$store.state.notification; },        set(value) { this.$store.commit('setNotification', value); },    },},

You can now bind to it with v-model="notification" as normal.

See Form Handling in the docs for more info.


Since this is a frequent thing that I do in my projects, I have written a helper function which generates the computed properties:

function mapStateTwoWay(...args) {    const result = {};    if (args.length === 1) {        for (const prop of Object.keys(args[0])) {            result[prop] = {                get() { return this.$store.state[prop]; },                set(value) { this.$store.commit(args[0][prop], value); },            };        }    } else {        for (const prop of Object.keys(args[1])) {            result[prop] = {                get() { return this.$store.state[args[0]][prop]; },                set(value) { this.$store.commit(args[0] + '/' + args[1][prop], value); },            };        }    }    return result;}

Use it like this:

computed: {    ...mapStateTwoWay({        notifications: 'setNotifications',        email: 'setEmail',    }),    // Namespaced    ...mapStateTwoWay('namespace', {        notifications: 'setNotifications',        email: 'setEmail',    }),}