【问题标题】:What is the right way to make API calls with Vuex?用 Vuex 进行 API 调用的正确方法是什么?
【发布时间】:2018-07-08 09:11:21
【问题描述】:

我有一个带有 Vuex 的 Vue Webpack 应用程序(我对这两者都是新手,来自 Ember 世界)。我目前已将其设置为使用 vue-resource 和这样的两个文件:

/src/store/api.js

import Vue from 'vue';
import { store } from './store';

export default {
  get(url, request) {
    return Vue.http
      .get(store.state.apiBaseUrl + url, request)
      .then(response => Promise.resolve(response.body))
      .catch(error => Promise.reject(error));
  },
  post(url, request) {
    return Vue.http
      .post(store.state.apiBaseUrl + url, request)
      .then(response => Promise.resolve(response))
      .catch(error => Promise.reject(error));
  },
  // Other HTTP methods removed for simplicity
};

然后我将上面的 api.js 文件导入到我的 /src/store/store.js 文件中,如下所示:

import Vue from 'vue';
import Vuex from 'vuex';
import Api from './api';

Vue.use(Vuex);

// eslint-disable-next-line
export const store = new Vuex.Store({
  state: {
    apiBaseUrl: 'https://apis.myapp.com/v1',
    authenticatedUser: null,
  },

  mutations: {
    /**
     * Updates a specific property in the store
     * @param {object} state The store's state
     * @param {object} data An object containing the property and value
     */
    updateProperty: (state, data) => {
      state[data.property] = data.value;
    },
  },

  actions: {
    usersCreate: (context, data) => {
      Api.post('/users', data)
        .then(response => context.commit('updateProperty', { property: 'authenticatedUser', value: response.body }))
        // eslint-disable-next-line
        .catch(error => console.error(error));
    },
  },
});

当我需要创建一个新用户时,我只需在我的组件中this.$store.dispatch('usersCreate', { // my data });。这工作得很好,但我有几个问题:

  1. 我无法捕获组件中的问题以显示 toast 消息等。 我什至无法检查 AJAX 调用是否成功。
  2. 如果我有很多 API,我将不得不在我的 store.js 文件中编写很多操作,这并不理想。我当然可以创建一个接受 HTTP 方法、URL 等的标准操作,然后调用它,但我不确定这是否是一个好习惯。

什么是正确的方法?如何在我调度操作的组件中检查 AJAX 失败/成功状态?使用 Vuex 时进行 API 调用的最佳做法是什么?

【问题讨论】:

  • 除非您的应用失控,否则我建议您不要这样做。

标签: javascript vue.js vuex vue-resource


【解决方案1】:

您的操作应该返回一个 Promise。您当前的代码只是调用 Api.post 而不返回它,因此 Vuex 不在循环中。请参阅 Vuex 文档中的示例以获取 Composing Actions

当你返回一个 Promise 时,动作调用者可以跟随 then() 链:

this.$store.dispatch('usersCreate').then(() => {
  // API success
}).catch(() => {
  // API fail
});

至于组织你的动作,你没有把它们都放在你的store.js文件中。 Vuex 支持模块/命名空间。 https://vuex.vuejs.org/en/modules.html

【讨论】:

    猜你喜欢
    • 2016-12-09
    • 2019-08-30
    • 2019-12-13
    • 2019-05-17
    • 2019-12-11
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    相关资源
    最近更新 更多