使用Vuex进行API调用的正确方法是什么?

Nag*_*Nag 8 javascript vue.js vue-resource vuex

我有一个Vue Webpack应用程序与Vuex(我是两个新人,来自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
};
Run Code Online (Sandbox Code Playgroud)

然后我将上面的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));
    },
  },
});
Run Code Online (Sandbox Code Playgroud)

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

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

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

Mat*_*att 11

你的行动应该返回一个承诺.您当前的代码只是调用Api.post而不返回它,因此Vuex不在循环中.请参阅Vuex docs for Composing Actions中的示例.

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

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

作为组织你的行为,你不要把它们都在你的store.js文件中.Vuex支持模块/命名空间.https://vuex.vuejs.org/en/modules.html