【问题标题】:Vuex state update is not updating DOMVuex 状态更新不更新 DOM
【发布时间】:2020-11-23 01:16:30
【问题描述】:

我有一组处于状态的对象

  hostInstances :  []

还有一个计算属性

getHostInstances(){
  return this.$store.state.hostInstances
}

它最初显示对象的确切数量,但如果我推送新的对象状态更改会显示在 vuedev 工具中,但计算属性不会更改。

我什至尝试通过计算属性获取 getter

  ...mapGetters(['getHostInstances' ]);

直接在dom中

v-for="instance in $store.getters.getHostInstances"

但它没有更新 dom。

【问题讨论】:

  • 你是如何推送新对象的?通过突变?状态只能通过突变来修改。
  • @rjcarl 是的,我通过突变对其进行了更新,并且在 vuedev 工具中可以清楚地看到 hostInstance 正在更新。
  • 在 OP 下面试试我的答案

标签: vuejs2 vuex


【解决方案1】:

你不需要 getter,因为你不会改变你的状态。您可以使用 Vuex 的 mapState 直接从商店获取它。仅当您不使用突变时,您还必须通过突变修改状态。

import { mapState } from 'vuex';

...
computed: {
   ...mapState(['hostInstances'])
},
methods: {
  addHostInstance() {
    this.$store.dispatch('addHostInstanceAction', yourHostInstanceObj);
  }
}

在你的店里……

export default new Vuex.Store({
  state: {...}
  actions: {
    addHostInstanceAction({commit}, payload) {
      commit('mutateInstances', payload);
    }
  },
  mutations: {
    mutateInstances(state, payload) {
      state.hostInstances.push(payload);
    }
  }
})

【讨论】:

    【解决方案2】:

    将您的 state 映射到 computed

    <template>
    
      <div v-for="instance in hostInstances">{{ instance }}</div>
    
    </template>
    
    <script>
    
    import { mapState } from `vuex`
    
    export default {
    
      computed: {
    
          ...mapState(['hostInstances'])
    
      }
    
    
    }
    
    </script>
    

    【讨论】:

      猜你喜欢
      • 2021-06-19
      • 2023-03-16
      • 2020-12-22
      • 2017-05-20
      • 2019-03-20
      • 2020-05-18
      • 2019-08-08
      • 1970-01-01
      • 2019-08-06
      相关资源
      最近更新 更多