Vue Vant中的輕提示 用axios攔截器封裝 全局使用


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中輕提示。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM