如何更新依赖于另一个状态异步数据的状态数据

时间:2020-10-17 23:06:00

标签: vue.js vuejs2 nuxt.js vuex

在Nuxt应用程序中,我有一个Vuex存储,该存储首先通过从外部URL进行获取来获取一些“属性”。我想使用此数据来更新另一个 状态元素称为“位置”,每个这些“属性”都有一个“位置”,但我不确定仅在获取所有属性后如何运行它。

export const mutations = {
    updateProperties: (state, properties) => {
        state.properties = properties
    },
    updateLocations: (state) => {
        const locationsArr = [...new Set( state.properties.map( property => property.acf.location_tab_group.location_table.city ) )]
        state.locations = locationsArr;
    }
}

export const actions = {

    async getProperties({ state, commit }) {
        if (state.properties.length) return
        try {
            let properties = await fetch(
                `https://...`
            ).then((res) => res.json())

            properties = properties
                .filter((el) => el.status === 'publish')
                .map(({ id, slug, title, acf }) => ({
                    id,
                    slug,
                    title,
                    acf,
                }))
            commit('updateProperties', properties)
            
        } catch (err) {
            console.log(err)
        }
    },

    getLocations({state, commit}) {
        if(state.properties.length) {
            const locationsArr = [...new Set( state.properties.map( property => property.acf.location_tab_group.location_table.city ) )]
            commit('updateLocations', locationsArr)
        }
    }
}

因此,基本上,我只想在获取所有属性后才知道如何调用“ updateLocations”突变。

1 个答案:

答案 0 :(得分:0)

在任何操作中,dispatch均可用于上下文对象。

如果我理解的正确,那么您想确保在致电getProperties之前已至少致电getLocations吗?

这是您在想的吗?

    async getLocations({state, commit, dispatch}) {
        if(!state.properties.length) {
            await dispatch('getLocations');
        }
        const locationsArr = [...new Set( state.properties.map( property => property.acf.location_tab_group.location_table.city ) )]
        commit('updateLocations', locationsArr);
    }