我有一个带有Vuex的Vue网页包应用程序(我对这两个应用程序都是新手,来自余烬世界).我目前已将其设置为使用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消息等.
  2. 如果我有很多API,我将不得不在我的应用store 中编写很多操作.这不是理想的js文件.我当然可以创建一个接受HTTP方法、URL等的标准操作,然后直接调用它,但我不确定这是否是一个好的实践.

正确的方法是什么?如何在我分派操作的组件中判断AJAX失败/成功状态?使用Vuex时进行API调用的最佳实践是什么?

推荐答案

你的行动应该回报你的promise .您当前的代码只调用Api.post而不返回它,因此Vuex已退出循环.请参见Vuex docs中的Composing Actions个示例.

当您回复promise 时,动作调用方可以遵循then()链:

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

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

Vue.js相关问答推荐

如何在AXIOS调用响应中动态导入视频并创建它的绝对路径?

如何在Vue3中使用vuechartjs 5.2从父组件更新图表

如何向 添加方法和 v-model?

如何解决 importers[path] is not a function for clean Vue 3/Vite/Storybook installation

作为props 传递的原始 ref 的 Vue 3 react 性

vue 不重新渲染数据更改

使用 Vue.js 清除数组内容和react性问题

将初始值设置为可直接在 HTML 中使用的 vue.js 模型

如何使用 vue.js 和 vue 路由实现当前路由的子菜单的子菜单

使用 v-slot:body 时 Vuetify v-data-table 没有响应

Express.js + lint 出错

Transition-group children must be keyed...but they are keyed

错误 [ERR_UNSUPPORTED_ESM_URL_SCHEME]:默认 ESM 加载器仅支持文件和数据 URL - Vue 3

Modal 内部的 Vue.js AJAX 调用

无法访问数据对象的嵌套属性

Nuxt.js - API 调用的最佳场所

将 SignalR 与 Vue.js 和 Vuex 集成

异步api调用后如何使用vuex getter

Axios 请求拦截器在我的 vue 应用程序中不起作用

在 Vue 应用程序中创建一个类的单个实例