我有一个带有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 });
.这很好,但我有几个问题:
- 我无法捕获组件中的问题以显示toast消息等.
- 如果我有很多API,我将不得不在我的应用store 中编写很多操作.这不是理想的js文件.我当然可以创建一个接受HTTP方法、URL等的标准操作,然后直接调用它,但我不确定这是否是一个好的实践.
正确的方法是什么?如何在我分派操作的组件中判断AJAX失败/成功状态?使用Vuex时进行API调用的最佳实践是什么?