首页 > 解决方案 > Vue / Vuex:计算内部的mapState未更新

问题描述

我正在尝试利用mapState反应性数据并遇到问题。我的Test.vue组件中有以下内容

 <template>
    <div> {{ name }} </div>
 </template>

computed: {
     ...mapState('user', ['age','name]
}

当我的状态user.name在组件之外更新时Test.vue,新值不会显示在里面Test.vue

例如,如果我通过我的突变进行更新userStore

[SET_USER_NAME_MUTATION](state, value) {
      state.name = value;
},


commit('SET_USER_NAME_MUTATION', "John")

当我检查 chrome DevTools 时,现在在我的 Vuex 商店中user { name: "John" },这是正确的

标签: vue.jsvuex

解决方案


您应该通过 vuex 操作来改变状态,而不是直接调用突变。尝试这样的事情,假设您的状态包含一个user具有name属性的对象:

Vue 组件

<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商店

// 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
}

无论如何,根据您的具体情况了解您的状态结构以更好的方法将非常有帮助


推荐阅读