vant 中的轻提示 用axios拦截器封装 全局使用
axios拦截器的两种方法
Interceptors
You can intercept requests or responses before they are handled by then
or catch
.
// Add a request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response;
}, function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});
request 请
求时,调用Vant的轻提示
Toast.loading({
message: '加载中...',
forbidClick: true,
});
然后 response中,清除轻提示
Toast.clear();
案例写法:
在封装的 axios中写
import axios from 'axios'
import {Toast} from 'vant'
const http = axios.create({
baseURL: 'https://m.maizuo.com',
timeout: 10000,
headers: {'X-Client-Info': '{"a":"3000","ch":"1002","v":"5.0.4","e":"1606313308132504036048897","bc":"430100"}'}
});
// Add a request interceptor
http.interceptors.request.use(function (config) {
//请求时调用轻提示
Toast.loading({
message: "加载莫急...",
forbidClick: true,
loadingType:'spinner',
duration:0
});
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
// Add a response interceptor
http.interceptors.response.use(function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
//响应时消除轻提示
Toast.clear();
return response;
}, function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});
export default http
目的:
为了调用数据的时候,进行加载样式的提示,将组件封装在axios中,每次请求axios数据的时候,可以调用Vant中轻提示。