【问题标题】:Vuex commit not updating stateVuex 提交不更新状态
【发布时间】:2019-08-08 11:01:21
【问题描述】:

我正在创建一个语言抽认卡应用程序,但在切换列表时遇到了状态更新问题。所以我看到在我的商店中,突变被触发了,但在我的 Vuex 开发工具中,尽管 vue 更新了一些,但状态没有注册更改......

HTML

<label style="margin-left: 5px">Word List</label>
<md-select id="list-select" v-model="currentList">
   <md-option v-for="(list, index) in wordLists" :key="index" :value="list.id">
       {{list.name}}
   </md-option>
</md-select>

JS 组件

import {mapGetters} from 'vuex';

...

computed: {
  ...mapGetters({
     showModalState: 'showModal',
     computedList: 'currentListWords',
     wordLists: 'wordLists'
  }),

...

watch: {
  currentList(val) {
     let list = this.wordLists.filter((v) => v.id === val).slice();

      this.$store.commit("setCurrentList", list);
      this.$store.commit("setTempList", list);
  }

...

JS 存储突变

setCurrentList(state, payload){
  state.currentList = payload;
},
setTempList(state, payload){
  state.tempList = payload;
},

JS 吸气剂

wordLists(state){
  return state.wordList;
},
currentList(state){
  return state.currentList;
},

商店

...
currentList: [],
wordLists: [],
...

【问题讨论】:

  • state.currentList 是一个对象吗?如果是这样,那么您将不得不使用 Vue.set 或 Object.assign
  • 它是一个数组中的对象...
  • 你描述了你在初始 vuex 状态下的属性吗? { state: () => ({ currentList: [], tempList: [] }) } 另外我认为您的属性名称有误

标签: vue.js vuex


【解决方案1】:

为了使更改具有反应性,您不能直接分配值。您将需要使用 Vue.set(如果要更新特定属性/索引的值)或 Object.assign(如果要更新完整对象)。详细了解 vue 反应性here

您必须在突变中执行以下操作以使您的更改具有反应性。

state.currentList = Object.assign({}, state.currentList, payload)

state.tempList = Object.assign({}, state.tempList, payload)

【讨论】:

    【解决方案2】:

    您是否在 Vuex 存储对象中添加了gettersstore.getters.showModalstore.getters.currentListWords 等。如果没有,请使用 mapState 而不是 mapGetters 来访问普通状态。

    【讨论】:

    • 对不起,我忘了添加那部分。我做到了。让我现在编辑!
    猜你喜欢
    • 1970-01-01
    • 2020-05-30
    • 2020-08-13
    • 2021-06-19
    • 2021-02-05
    • 2020-11-23
    • 2022-01-16
    • 2020-12-22
    • 2023-03-16
    相关资源
    最近更新 更多