【问题标题】:How to update state data that is dependant on another state async data如何更新依赖于另一个状态异步数据的状态数据
【发布时间】:2020-10-17 23:06:00
【问题描述】:

在 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”突变。

【问题讨论】:

    标签: vue.js vuejs2 nuxt.js vuex


    【解决方案1】:

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

    如果我的理解正确,您想确保在调用 getLocations 之前至少调用了一次 getProperties

    这就是你的想法吗?

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多