【问题标题】:Why is computed value not updated after vuex store update?为什么 vuex 存储更新后计算值不更新?
【发布时间】:2016-12-13 15:26:22
【问题描述】:

我得到了一个 printerList 计算属性,应该在 getPrinters() 解析后重新评估它,但看起来不是。

sources are onlineoptbox.component.vuevuexoptboxes.service.js

组件

<template>
    <div v-for="printer in printersList">
        <printer :printer="printer" :optbox="optbox"></printer>
    </div>
</template>
<script>
…
created() { this.getPrinters(this.optbox.id); },
    computed: {
        printersList() {
            var index = optboxesService.getIndex(this.optboxesList, this.optbox.id);
            return this.optboxesList[index].printers
        }
    },
    vuex: {
        actions: { getPrinters: actions.getPrinters,},
        getters: { optboxesList: getters.retrieveOptboxes}
    }
<script>

动作

getPrinters({dispatch}, optboxId) {
    printers.get({optbox_id: optboxId}).then(response => {
        dispatch('setPrinters', response.data.optbox, response.data.output.channels);
    }).catch((err) => {
        console.error(err);
        logging.error(this.$t('printers.get.failed'))
    });
},

突变

setPrinters(optboxes, optboxId, printers) {
    var index = this.getIndex(optboxes, optboxId);
    optboxes[index] = {...optboxes[index], printers: printers }
},

问题

为什么不重新评估 printerList 计算属性(即 v-for 为空)

【问题讨论】:

  • vuex 调试器是否显示Printers 的正确值?对我来说,它敲响了警钟,突变正在传递状态而不是自己处理它。
  • @HectorLorenzo 如果你的意思是 vue devtools 工具,是的,但它没有提交

标签: vue.js computed-properties vuex


【解决方案1】:

这是由于这一行: optboxes[index] = {...optboxes[index], printers: printers }.

您是直接设置带有索引的项目,can't be observed by Vue

尝试从数组中拼接旧项并推送新项。

【讨论】:

  • 拼接对我有用。例如,在我的突变中: state.orders.splice(index, 1, payload)
【解决方案2】:

你可以这样做:

Vue.set(optboxesList[index], 'printers', printers )

【讨论】:

  • 这是为我解决的问题。我直接从我的突变中设置状态。一旦我开始使用 Vue.set,一切都会再次神奇地反应
【解决方案3】:

你需要强制更新

setPrinters(optboxes, optboxId, printers) {
    const index = this.getIndex(optboxes, optboxId);
    const newVal = {...optboxes[index], printers: printers }
    Vue.set(optboxes, index, newVal);
},

【讨论】:

    猜你喜欢
    • 2021-07-09
    • 2021-04-16
    • 2020-11-12
    • 2019-10-05
    • 2017-03-23
    • 2019-09-01
    • 2019-01-28
    • 2018-11-29
    • 2019-10-19
    相关资源
    最近更新 更多