vue.js - 哪个生命周期钩子是调度 API 获取请求的最佳实践?
问题描述
我只是想知道 Vue.js 社区目前是否就使用哪个生命周期挂钩来调度 API 获取操作达成共识?
例如,我有一个动作,例如在我的Vuex
商店:
...
actions: {
fetchAccount: async ({ commit }, payload) => {
await Vue.prototype.$API.fetchAccount(payload).then((response) => {
commit("SET_ACTIVE_ACCOUNT", response.data);
});
},
}
...
该操作被传递给服务:
import { axios } from "@/services/http";
import { EventEmitter } from "events";
class accountServiceAPI extends EventEmitter {
constructor() {
super();
this.accessToken = "";
}
fetchAccount(payload) {
return new Promise({resolve, reject} => {
axiosWave.get(`api//v2/accounts/retrieve/${payload.accountUUID}`, { headers: {} }).then(response => {
if (response.success) {
resolve(response.data);
} else {
reject(response.data);
}
}).catch(error => {
reject(error.response);
});
});
}
}
const accountServiceAPI = new accountServiceAPI();
accountServiceAPI.setMaxListeners(5);
export default accountServiceAPI;
我通常会在需要数据的组件的生命周期钩子中分派它created()
......但肯定必须有一种更高效的方式吗?
解决方案
您可以早在created()
. mounted()
当实例已经安装或渲染时调用。您通常会在此处进行与 UI 相关的设置。
此外,您可以fetchAccount
像这样改进操作:
fetchAccount: async ({ commit }, payload) => {
const { data } = await Vue.prototype.$API.fetchAccount(payload);
commit("SET_ACTIVE_ACCOUNT", data);
}
推荐阅读
- javascript - 如何修复“selenium.common.exceptions.JavascriptException:消息:javascript 错误:$ 未定义”
- kubernetes - 如何将日志从 kubernetes pod 发送到主机 pc
- python - discord.py,sqlite | 邀请记录器
- systemd - 停止显示消息但转发到系统日志
- swift - Xcode 12 不从 outlet 读取数据,不进行颜色编码和自动填充
- javascript - 如何遍历数组数组并检查它们是否具有另一个数组 + 前缀的值?
- android-studio - 如何从活动结果 API 获取 requestCode
- reactjs - 类型错误模块 '"react-leaflet"' 没有导出的成员 'useEventHandlers'
- html - 如何从 django 项目中的 unsplash 源上传图像?
- c# - 这样写任务收益回报可以吗?