【发布时间】:2020-04-16 06:56:10
【问题描述】:
目前我们有 Vue + Vuex 应用程序,每个页面使用大量自定义组件。我们使用 MongoDB 作为数据库。
每个组件从 API 端点加载一些初始化数据:
async loadData() {
const data = await getData('/api/some_url', {path_in_db: 'some.path.to.db')
}
现在我们遇到了一个问题,即在页面初始化期间有超过 50 个请求发送到后端服务器。
我尝试做的事情:
创建 Vuex 商店
import { INITIAL_DATA_GET, INITIAL_DATA_SET, INITIAL_DATA_CLEAR } from './actions';
const getDefaultState = () => {
return {};
};
const mutations = {
[INITIAL_DATA_SET]: (mutationState, obj) => {
const { request = {} } = mutationState;
if (!request[obj.ref]) {
request[obj.ref] = { paths: [] };
}
request[obj.ref].paths.push(obj.resPath);
Vue.set(mutationState, 'request', request);
},
[INITIAL_DATA_CLEAR]: (mutationState) => {
Vue.set(mutationState, getDefaultState());
},
};
const actions = {
[INITIAL_DATA_SET]: ({ commit }, obj) => {
commit(INITIAL_DATA_SET, obj);
},
[INITIAL_DATA_CLEAR]: ({ commit }) => {
commit(INITIAL_DATA_CLEAR);
},
};
const getters = {
[INITIAL_DATA_GET]: getterState => getterState,
};
从我运行的每个组件
store.dispatch(INITIAL_DATA_SET, {
ref: this.ref,
resPath: this.resPath,
});
所有组件初始化后,最后一个console.log(mutationState)看起来像这样
getters: {
request: {
5d879e7af0a317002e5b4759: {
paths: ['path.to.a', 'path.to.b', 'path.to.c'...]
}
}
}
我的问题是:
- 有什么方法可以等待所有组件加载完毕,然后才向数据库发送一个请求?
- 实现此类(获取多个请求)的最佳做法是什么?
- 最佳方案是什么:发送一个大请求还是多个小请求?
【问题讨论】: