在 Vue.js 中使用带有单独服务的 axios?

Using axios in Vue.js with separate service?

我想将 axios 请求逻辑移动到我的 Vue.js 应用程序中的单独服务。 Axios 总是 returns 承诺,我如何在我的组件中从它获取响应数据?或者可能有其他一些解决方案?

UserService.js

class UserService {
    getUser() {
        const token = localStorage.getItem('token');
        return axios.get('/api/user', {
            headers: {
                'Authorization': 'Bearer ' + token
            }
        }).then(function (response) {
            return response.data;
        }).catch(function (error) {
            console.log(error);
        });
    }
    getUserTasks() {
        const token = localStorage.getItem('token');
        return axios.get('/api/user/task', {
            headers: {
                'Authorization': 'Bearer ' + token
            }
        }).then(response => {
            return response;
        }).catch(function (error) {
            console.log(error);
        });
    }
    get currentUser() {
        return this.getUser();
    }
}
export default new UserService();

您可以 return 来自请求模块的承诺并在任何地方使用它。例如,

sendGet(url) {
    const token = localStorage.getItem('token');
    return axios.get(url, {
        headers: {
            'Authorization': 'Bearer ' + token
        }
    })
}

因为我们没有在 axios 结果上调用 .then,promise 不会被解析。相反,promise 本身将从这个方法 returned。因此可以如下使用,

getUser() {
  axiosWrapper.sendGet('/api/user')
    .then((response)=> {
        // handle response
    })
    .catch((err)=>{
        // handle error
    })
}

但是,如果您使用 vuex 或 redux 之类的状态管理解决方案,则可以将异步操作与状态管理器结合使用以实现更好的控制。 如果您使用的是 redux,则可以使用 redux thunk 或 redux-saga 帮助程序库。如果您使用的是 vuex,则可以在操作中处理此类副作用(请参阅此处https://vuex.vuejs.org/en/actions.html