I don't quite understand what you mean by encapsulation. This is the class I've dealt with briefly before
.
import axios from 'axios';
import { Helper } from '../helper';
declare var Promise: any;
export class Request {
static _instance: Request;
static getInstance() {
this._instance || (this._instance = new Request());
return this._instance;
}
config: any;
constructor() {
axios.interceptors.request.use(function (config) {
// Header
// url
config.url = `https://.../${config.url}`
return config;
});
axios.interceptors.response.use((response) => {
//
return response.data;
}, (error) => {
if (error.response.status == 401) {
//
}
else if(error.response.status == 400) {
// alert
}
return Promise.reject(error);
});
}
get(uri: string, config: object = {}) {
return axios.get(uri, config);
}
post(uri: string, data: any = {}, config: object = {}) {
return axios.post(uri, data, config);
}
put(uri: string, data: any, config: object = {}) {
return axios.put(uri, data, config);
}
delete(uri: string, config: object = {}) {
return axios.delete(uri, config);
}
}
do you mean to rewrite a axios
or axios
to encapsulate the data in a parameter format?
does axios have to be sealed again? It should be customized. Generally speaking, writing some interceptors logic is enough to cope with 90% of the scenarios.
< hr >
updated
well, after reading some articles in your updated description, I think there is no optimal solution for this kind of partial customized encapsulation. As the saying goes, radish and green vegetables have their own preferences. You like to handle exceptions this way, but I like to handle exceptions so that it is difficult to choose. Moreover, after reading the so-called encapsulation in some articles, we have to forcibly introduce the Message components in element-ui to make the packaged things more coupled with a specific project. It does not have generality in a broad sense.
the way I am currently using is
axios is mainly used to intercept request, response, interfaces. Just provide the address and parameters
as for the messages prompts you want, I think they should be done in vuex
.
GET_USER: state => {
state.loading = true;
}
GET_USER_SUCCESS: state => {
state.loading = false;
}
then for loading
display load animation
After looking at
, I feel that "the encapsulation of Axios in vue and the management (update) of API interface" should be one of the solutions that best meet my needs
.