美文网首页
axios封装

axios封装

作者: 正在成长的切图仔 | 来源:发表于2021-04-22 18:16 被阅读0次

    第一步:配置axios

    首先,创建一个axios.js,这里面存放的时axios的配置以及拦截器等,最后导出一个axios对象。我平常elementUI用的比较多,这里你也可以使用自己的UI库。

        import axios from 'axios'
        import {MessageBox} from 'element-ui'
        //请求拦截
        axios.interceptors.request.use(config => {
            config.timeout = 15000
            return config
        }, error => {
            return Promise.reject(error)
        })
        //响应拦截
        axios.interceptors.response.use(response => {
            return response
        }, error => {
            return Promise.resolve(error.response)
        })
    
        function checkStatus (response) {
            // loading
            if(response == undefined ){
                alert('请求超时')
            }
            // 如果http状态码正常,则直接返回数据
            if (response.data.State === 400) {
                alert(response.data.Msg)
                return false
            }
            if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
                return response
                // 如果不需要除了data之外的数据,可以直接 return response.data
            }
            // 异常状态下,把错误信息返回去
            return {
                status: -404,
                msg: alert('404')
            }
        }
        export default {
            post (url, data) {
                return axios({
                    method: 'post',
                    url,
                    data,
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        // "token":'14a1347f412b319b0fef270489f'
                    }
                }).then(
                    (response) => {
                        return checkStatus(response)
                    }
                )
            },
            get (url, params) {
                return axios({
                    method: 'get',
                    url,
                    params, // get 请求时带的参数
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                }).then(
                    (response) => {
                        return checkStatus(response)
                    }
                )
            }
        }
    

    页面使用

    <script>
    import axios from '../../utils/axios'
    export default {
      methods:{
        async getTeachingMaterials() {
          let params = {}
          const res = await axios.post('http://',params)
        },
      }
    }
    </script>
    

    如果需要吧 Loading 封装进来

    首先创建 loading.js

    import { Loading } from 'element-ui';
    let loadingCount = 0;
    let loading;
    
    const startLoading = () => {
      loading = Loading.service({
        lock: true,
        text: '拼命加载中...',//可以自定义文字
        spinner:'el-icon-loading',//自定义加载图标类名
        background: 'rgba(255,255,255,.4)',//遮罩层背景色
        target:'#content-box'//选定模态框遮罩DOM
      });
    };
    
    const endLoading = () => {
      loading.close();
    };
    
    export const showLoading = () => {
      if (loadingCount === 0) {
        startLoading();//开启加载框
      }
      loadingCount += 1;//请求进来加一
    };
    
    export const hideLoading = () => {
      if (loadingCount <= 0) {
        return;
      }
      loadingCount -= 1;//请求响应减一
      if (loadingCount === 0) {
        endLoading();//接口加载完关闭
      }
    };
    
        import axios from 'axios'
        import {MessageBox} from 'element-ui'
        import { showLoading, hideLoading } from './loading';
        //请求拦截
        axios.interceptors.request.use(config => {
            showLoading()//开启
            config.timeout = 15000
            return config
        }, error => {
            return Promise.reject(error)
        })
        //响应拦截
        axios.interceptors.response.use(response => {
            setTimeout(()=>{
                hideLoading()//关闭
            },1000)
            return response
        }, error => {
            return Promise.resolve(error.response)
        })
    
        function checkStatus (response) {
            // loading
            if(response == undefined ){
                alert('请求超时')
                hideLoading();
            }
            // 如果http状态码正常,则直接返回数据
            if (response.data.State === 400) {
                alert(response.data.Msg)
                return false
            }
            if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
                return response
                // 如果不需要除了data之外的数据,可以直接 return response.data
            }
            // 异常状态下,把错误信息返回去
            return {
                status: -404,
                msg: alert('404')
            }
        }
        export default {
            post (url, data) {
                return axios({
                    method: 'post',
                    url,
                    data,
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        // "token":'14a1347f412b319b0fef270489f'
                    }
                }).then(
                    (response) => {
                        return checkStatus(response)
                    }
                )
            },
            get (url, params) {
                return axios({
                    method: 'get',
                    url,
                    params, // get 请求时带的参数
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                }).then(
                    (response) => {
                        return checkStatus(response)
                    }
                )
            }
        }
    

    当然也可以吧ipi封装一下小伙伴们可以自己尝试一下新建一个api.js

    相关文章

      网友评论

          本文标题:axios封装

          本文链接:https://www.haomeiwen.com/subject/vrefrltx.html