我将 TypeScript 与 Vue/Vuex 结合使用来创建一个玩具应用程序,其中我需要在渲染组件时从远程 API 加载项目列表。在下面的操作中,我使用库 axios
发出 http 请求,并将其作为 promise 返回:
const actions = {
getCurrentSession(context: Context) {
return axios.get("http://localhost:3000/sessions/current")
.then((res) => {
commitSharedFiles(context, res.data.shared_files);
})
.catch((e: string) => {
console.error(e);
});
}
};
// export action
export const dispatchGetSharedFiles = dispatch(actions.getCurrentSession);
// commit
export const commitSharedFiles = commit(mutations.setSharedFileList);
// mutations to the state tree
const mutations = {
setSharedFileList(state: State, sharedFiles: StoreState.DirFile[]) {
state.sharedFileList = sharedFiles;
}
};
由于操作的异步性质,我必须在从存储/状态树中检索获取的文件列表之前解决 promise :
// this is called in the mounted() life cycle method:
Store.dispatchGetSharedFiles(this.$store).then(res => {
this.sharedFiles = Store.readSharedFilesList(this.$store);
});
这个是可以的,但是我觉得resolve promise然后获取数据很费脑筋。有没有更好的方式在 Vuex 中使用异步操作?谢谢
最佳答案
使用 async/await
作为操作,使用映射的 getter
从商店中检索项目(也可以映射操作)。
// store.ts
const actions = {
async FetchSharedFiles(context: Context) {
// omitted error handling for brevity
let {res} = await axios.get("http://localhost:3000/sessions/current")
commitSharedFiles(context, res.data.shared_files);
}
};
// component.ts
import { mapGetters } from 'vuex'
...
mounted () {
// again, do any necessary error handling
this.$store.dispatch('FetchSharedFiles')
},
computed: {
...mapGetters({
sharedFiles: 'namespace/getSharedFiles'
})
}
使用此模式受益于 vuex 的 react 性,因此组件中的 sharedFiles
将在操作完成并提交响应数据时触发更新。您的模板可能如下所示:
<template>
<div v-for="(file, i) in sharedFiles" :key="i">
// layout for each item...
</div>
</template>
关于typescript - Vuex:通过对 REST API 的 promise 调用处理异步操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49849725/