[Vuejs]-Vue/Vuex: mapState inside computed is not updating

0👍

You should mutate state through vuex actions instead of directly calling the mutation.
Try with something like this, assuming your state contains a user object with name property:

Vue component

<template>
    <div> 
        <span>{{ name }}</span> 
        <button @click="changeName">Change name</button>
    </div>
 </template>

<script>
import { mapState } from 'vuex'

export default {
    name: 'MyComponent',

    computed: {
        ...mapState({
            name: state => state.user.name
        })
    },

    methods: {
        changeName () {
            this.$store.dispatch('changeName', 'John Smith')
        }
    }
}
</script>

Vuex store

// state
const state = {
    user: {
        name: null
    }
}

// getters
const getters = {
    // ...
}

// actions
const actions = {
    changeName ({ commit }, payload) {
        commit('setName', payload)
    }
}

// mutations
const mutations = {
    setName (state, payload) {
        state.user.name = payload
    }
}

export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations
}

Anyway, it will be very helpful to know your state structure to a better approach as per your specific case

Leave a comment