【问题标题】:Which life cycle hook is best practise to dispatch an API fetch request with?哪个生命周期钩子是调度 API 获取请求的最佳实践?
【发布时间】:2020-06-12 17:01:57
【问题描述】:

我只是想知道 Vue.js 社区目前是否就使用哪个生命周期挂钩来调度 API 获取操作达成共识?

例如,我有一个动作比如在我的Vuex store:

  ...
  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.js vuex


【解决方案1】:

您可以早在created() 中从 API 获取并操作您的数据/状态。 mounted() 在实例已经安装或渲染时调用。您通常会在这里进行与 UI 相关的设置。

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

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

【讨论】:

  • 感谢 Alphonsus,感谢您对此的回答。
猜你喜欢
  • 1970-01-01
  • 2018-09-09
  • 1970-01-01
  • 1970-01-01
  • 2020-03-20
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
相关资源
最近更新 更多