Why is computed value not updated after vuex store update?

蓝咒 提交于 2019-12-10 12:32:14

问题


I got a printerList computed property that should be re-evaluated after getPrinters() resolve, but it look like it's not.

sources are online: optbox.component.vue, vuex, optboxes.service.js

Component

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

Actions

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'))
    });
},

Mutations

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

Question

Why does the printerList computed property isn't re-evaluated (i.e. the v-for is empty)


回答1:


It is due to this line: optboxes[index] = {...optboxes[index], printers: printers }.

You are directly setting item with index, which can't be observed by Vue

Try splicing the old item from array and pushing the new one.




回答2:


You could do this:

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


来源:https://stackoverflow.com/questions/38819289/why-is-computed-value-not-updated-after-vuex-store-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!