首页 > 解决方案 > 哪个生命周期钩子是调度 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()......但肯定必须有一种更高效的方式吗?

标签: vue.jsvuex

解决方案


您可以早在created(). mounted()当实例已经安装或渲染时调用。您通常会在此处进行与 UI 相关的设置。

此外,您可以fetchAccount像这样改进操作:

fetchAccount: async ({ commit }, payload) => {
  const { data } = await Vue.prototype.$API.fetchAccount(payload);
  commit("SET_ACTIVE_ACCOUNT", data);
}

推荐阅读