vue.js - 如何更新依赖于另一个状态异步数据的状态数据
问题描述
在 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”突变。
解决方案
在任何操作中,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);
}
推荐阅读
- flutter - 颤振 | 禁用按钮的 onPressed 直到当前通话结束
- php - php openssl 非对称解密
- php - 在 Laravel 8 中创建带有外观的自定义包
- python - 当我使用枕头模块截取一张截图时,我该怎么办?
- javascript - 使用 sinon 监视/存根 document.submit()
- favicon - favicon 不会显示在桌面快捷方式上,仅显示在选项卡中
- python - 正则表达式:标记模式
- delphi - Delphi 10.4 - DataSnap - 并行调用 - [FireDAC][Phys][SQLite]-326。无法执行该操作,因为上一个操作正在进行中
- javascript - 多个样式表不适用于 Webpack 5.11.0
- gridview - 如何向 yii2 kartik CheckBoxColumn 添加自定义操作