zoukankan      html  css  js  c++  java
  • Vue-cli3 axios路由拦截 并使用

    1.安装axios (在项目中)

    npm i axios
    

      

    2.创建axios.intercept.js  内容如下

    // 配置axios拦截器
    import axios from 'axios';
    import store from '../store'; // 追加token
    // 创建axios实例
    const service = axios.create({
        // baseURL: process.env.VUE_APP_URL, // api 的 VUE_APP_URL
        timeout: 50000 // 请求超时时间
    });
    // request拦截器,在请求之前做一些处理
    service._requestCount = 0; // 接口请求累加
    service.interceptors.request.use(
        config => {
            service._requestCount++;
            store.commit('handleLoading', true); // 接口请求loading
            return config
        },
        error => {
            console.log(error) // for debug
            Promise.reject(error)
        }
    )
    
    // response 拦截器,数据返回后进行一些处理
    service.interceptors.response.use(
        response => {
            service._requestCount--;
            if(service._requestCount<=0){ // 如果接口请求累加值小于0 那么关闭loading
                store.commit('handleLoading', false);
            }
            const res = response.data;
            return res;
        },
        error => {
            service._requestCount--;
            if(service._requestCount<=0){
                store.commit('handleLoading', false);
            }
            Promise.reject('异常', error);
        }
    )
    export default service
    

      

    3.使用拦截器

    创建接口请求模块 例如 UserRequest.js

    import service from './axios.intercept'; // 导入刚才 创建的拦截器
    
    const interfaceAddress = process.env.VUE_APP_URL + '/user'; // 全局请求地址
    const requestInterfaceList = {
        queryUsers: interfaceAddress + '/users', // 具体接口地址
        queryUserDetails: interfaceAddress + '/users/details'
    }
    
    export const UserRequest {
        queryUsers(params){
            const sendObj = {};
            ({
                pageNo: sendObj.pageNo,// 页码
                pageSize: sendObj.pageSize,// 每页条数
                shopCodeOrName: sendObj.shopCodeOrName,// 网点code或名称关键字
            } = params);
            return service({
                url: requestInterfaceList.queryUsers,
                method: 'get',
                params: sendObj
            })
        }
    }        
    

      

    4.使用 封装好的 接口请求

    import {UserRequest} from "../../../../apis/UserRequest"; // 导入刚才写的UserRequest.js
    
    在组件中使用
    export default {
            name: "app-invoicing-record",
            created(){
               // 使用
               UserRequest.queryUsers({id: 1234}).then(res=>{});
            }
    }    
    

      

  • 相关阅读:
    Docker学习总结(四)--应用部署
    strcat的由来
    ubuntu man不到pthread_mutex_XX
    string::front
    string::find_last_of
    string::find_last_not_of
    string::find_first_of
    string::find_first_not_of
    string::erase
    string::empty
  • 原文地址:https://www.cnblogs.com/MainActivity/p/12097199.html
Copyright © 2011-2022 走看看