【问题标题】:Vue/Vuex: mapState inside computed is not updatingVue / Vuex:计算内部的mapState未更新
【发布时间】:2021-11-05 14:02:41
【问题描述】:

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

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

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

当我的状态user.nameTest.vue 组件之外更新时,新值不会显示在Test.vue 内部。

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

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


commit('SET_USER_NAME_MUTATION', "John")

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

【问题讨论】:

  • 显示您如何更新user.name。你用的是什么版本的 Vue?
  • 刚刚更新...我正在通过user 商店中的突变更新状态。另外,使用 Vue 2
  • 你能分享一个重现问题的链接吗?
  • 我假设...mapState('user', ['age','name] 末尾缺少的' 存在于您的实际代码中?

标签: vue.js vuex


【解决方案1】:

您应该通过 vuex 操作来改变状态,而不是直接调用突变。 尝试使用类似的方法,假设您的状态包含具有 name 属性的 user 对象:

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
}

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

【讨论】:

    猜你喜欢
    • 2018-05-03
    • 2017-04-11
    • 2019-09-25
    • 2019-10-19
    • 2020-08-11
    • 2021-07-04
    • 2020-05-22
    • 1970-01-01
    • 2019-05-23
    相关资源
    最近更新 更多