Vuex getter使用v-for填充组件

时间:2018-03-05 20:32:11

标签: javascript vue.js vuejs2 vue-component vuex

我正在使用vuex store对象构建vue2组件。该组件如下所示:

<template>
    <ul id="display">
        <li v-for="item in sourceData()">
            {{item.id}}
        </li>
    </ul>
</template>

<script>  
    export default {
        mounted: function () {
            console.log('mounted')
        },
        computed: {
            sourceData: function() {
                return this.$store.getters.visibleSource
            }
        }
    }
</script>

在主要的javascript条目中,在流程开始时通过ajax调用填充商店:

new Vue({
    store,
    el: '#app',
    mounted: function() {
        this.$http.get('/map/' + this.source_key + '/' + this.destination_key)
            .then(function (response) {
                store.commit('populate', response.data)
            })
            .catch(function (error) {
                console.dir(error);
            });
    }
});

我没有看到任何错误,当我使用Vue devtools资源管理器时,我可以看到我的组件sourceData属性中填充了数百个项目。我希望在填充此数据后,我会在页面上看到一堆liitem.id

但是,尽管组件中没有错误和明显好的数据,但我没有看到模板呈现任何内容。

在填充vuex存储后,是否需要使用某种回调来触发组件?

编辑:添加商店代码:

import Vue from 'vue';
import Vuex from 'vuex';
import { getSource, getDestination } from './getters'

Vue.use(Vuex)

export const store = new Vuex.Store({
    state: {
        field_source: [],
        field_destination: []
    },
    getters: {
        visibleSource: state => {
            // this just does some formatting 
            return getSource(state.field_source)
        },
        visibleDestination: state => {
            return getDestination(state.field_destination)
        }
    },
    mutations: {
        populate(state, data) {
            state.field_source = data.source
            state.field_destination = data.destination
        }
    }
})

EDIT2:也许它不是v-for的问题 - 我没有看到正在呈现的模板中的任何内容,甚至不是主ul标记,我和#39;即使脚本中存在问题,也希望看到(空)。

1 个答案:

答案 0 :(得分:1)

sourceData是计算属性,而不是方法。您不需要调用它。请勿像v-for="item in sourceData()"一样使用它,请像v-for="item in sourceData"一样使用它。

除此之外,在您的'populate'突变上,您正在覆盖观察/反应对象。

使用Vue.set()

mutations: {
    populate(state, data) {
        // was state.field_source = data.source
        Vue.set(state, 'field_source', data.source);
        // was state.field_destination = data.destination
        Vue.set(state, 'field_destination', data.destination);
    }
}

将所有元素推送到现有的,observe / reactive,arrays:

mutations: {
    populate(state, data) {
        // was state.field_source = data.source
        state.field_source.push(...data.source);
        // was state.field_destination = data.destination
        state.field_destination.push(...data.destination);
    }
}