← 返回首页
Vue-cli3基础教程(二十一)
发表时间:2022-08-15 23:44:18
axios封装

项目开发中通常需要封装axios,简化操作。

实现代码:


//这里我们对axios进行简单的封装。
import axios from 'axios' //引入 axios
import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";

// 创建 axios 实例
const http = axios.create(
    {
      timeout: 60000, // 请求超时时间
    }
)

http.get = (url, params)=>{
    const config = {
        method: 'get',
        url: url
    }
    if (params) config.params = params
    return http(config)
}

//长get请求
http.lget = (url,params,loading)=>{
    let options = {
            lock: true,
            text: loading,
            spinner: "el-icon-loading",
            background: "rgba(255,255,255,0)",
            customClass: "loadingMask",
    },
    loader = ElementUI.Loading.service(options)
    const config = {
        method: 'get',
        url: url,
        timeout: 600000
    }
    if (params) config.params = params
    return http(config).then(resp=>{
        loader.close();
        return resp;
    })
}

http.post = (url, params)=>{
    const config = {
        method: 'post',
        url: url
    }
    if (params) config.data = params
    return http(config)
}

//长post请求
http.lpost = (url,params,loading)=>{
    let options = {
            lock: true,
            text: loading,
            spinner: "el-icon-loading",
            background: "rgba(255,255,255,0)",
            customClass: "loadingMask",
        },
        loader = ElementUI.Loading.service(options)
    const config = {
        method: 'post',
        url: url,
        timeout: 600000
    }
    if (params) config.data = params
    return http(config).then(resp=>{
        loader.close();
        return resp;
    })
}



http.put = (url, params)=>{
    const config = {
        method: 'put',
        url: url
    }
    if (params) config.data = params
    return http(config)
}

http.delete = (url, params)=>{
    const config = {
        method: 'delete',
        url: url
    }
    if (params) config.params = params
    return http(config)
}

//导出
export default http