简体   繁体   English

Vue反应性问题

[英]Vue reactivity issue

I am trying to concat 2 arrays of arrays, but there is no effect because of async fetching one of them. 我正在尝试连接2个数组的数组,但是由于异步获取其中之一而没有效果。

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

Getter above is being set after some ms (server response) so when this assignment is triggered, getter is empty. 上面的getter将在ms(服务器响应)后设置,因此当触发该分配时,getter为空。 When state is set (server responded), array 'subcategories' should be updated but it is not (but getter is). 设置状态(服务器响应)后,应更新数组“子类别”,但不进行更新(但使用getter进行更新)。 How to solve it? 怎么解决呢?

More code: 更多代码:

getter: 吸气:

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

actions: 动作:

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

mutation which updates subcategoryIds: 更新subcategoryIds的突变:

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

Create a computed for the subcategories: 为子类别创建一个计算式:

computed: {
    subcategories() {
        return [...this.subcategories, ...[ this.$store.getters['categories/subcategoriesOfCurrent'] ]];
    }
}

since computed props are reactive, it will change the result each time the getter changes 由于计算的道具是反应性的,因此每次吸气剂改变时,它都会改变结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM