【发布时间】: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 });。这工作得很好,但我有几个问题:
- 我无法捕获组件中的问题以显示 toast 消息等。 我什至无法检查 AJAX 调用是否成功。
- 如果我有很多 API,我将不得不在我的 store.js 文件中编写很多操作,这并不理想。我当然可以创建一个接受 HTTP 方法、URL 等的标准操作,然后调用它,但我不确定这是否是一个好习惯。
什么是正确的方法?如何在我调度操作的组件中检查 AJAX 失败/成功状态?使用 Vuex 时进行 API 调用的最佳做法是什么?
【问题讨论】:
-
除非您的应用失控,否则我建议您不要这样做。
标签: javascript vue.js vuex vue-resource