Vue反应性问题

时间:2017-11-13 09:07:38

标签: javascript vue.js vuex

我试图连接2个数组数组,但由于异步获取其中一个数组没有效果。

this.subcategories = [...this.subcategories, ...[ this.$store.getters['categories/subcategoriesOfCurrent'] ]]; 

上面的getter是在ms(服务器响应)之后设置的,因此当触发此赋值时,getter为空。当设置状态(服务器响应)时,数组'子类别'应该更新,但它不是(但是getter是)。怎么解决?

更多代码:

吸气剂:

subcategoriesOfCurrent: (state: CategoriesState, getters: any) => {
        return (getters.current && getters.current.subcategoryIds) ?
            getters.current.subcategoryIds.map((id: string) => getters.all[id]) : [];
    }

动作:

setCategory: ({ commit, dispatch }: ActionArgs, categoryId: string) => {
        commit('setCategory', categoryId); //sets current category Id
        dispatch('fetchSubcategories', categoryId); //fetching from server which commits updateCategorySubcategories
    },



fetchSubcategories: ({ dispatch, commit }: ActionArgs, parentId: string): void => {
            HttpService.getInstance().get(`/categories?parent_id=${parentId}`).subscribe(
                result => {
                    commit('updateCategories', result.data);
                    commit('updateCategorySubcategories', { parentId, categories: result.data });
                }
            );
        },
更新子类别的

变异:

updateCategorySubcategories: (state: CategoriesState, { parentId, categories }: { parentId: string; categories: Category[] }): void => {
        Vue.set(state.categories[state.currentCategoryId], 'subcategoryIds', categories.map(category => category.id));
    },

1 个答案:

答案 0 :(得分:1)

为子类别创建计算:

generic-pool

因为计算出的道具是反应性的,所以每次吸气剂改变时它都会改变结果