vue cli3 使用axios和elementui 实现 全局请求的loading

原文链接: vue cli3 使用axios和elementui 实现 全局请求的loading

上一篇: uml 用例图

下一篇: idea 创建 kotlin hello 项目

实现全局请求的loading

项目结构

52e2398d026a46c4074aa9873ce10346691.jpg

http.js

封装axios, 设置全局拦截器,使用全局变量, 显示和关闭loading

import axios from "axios";
import { Loading, Message } from "element-ui";

// 全局变量 保存 loading实例
let loading;

function startLoading() {
  console.log("startLoading");
  loading = Loading.service({
    lock: true,
    text: "加载中...",
    background: "deepgray"
  });
}

function endLoading() {
  console.log("endLoading");
  loading.close();
}

// 请求拦截
axios.interceptors.request.use(
  config => {
    startLoading();
    return config;
  },
  error => Promise.reject(error)
);

// 响应拦截
axios.interceptors.response.use(
  response => {
    endLoading();
    return response;
  },
  error => {
    endLoading();
    Message.error("加载错误");
    return Promise.reject(error);
  }
);
export default axios;

vue.config.js

配置cros代理, 将以/ahao开始的请求使用代理访问,实现 前端跨域

module.exports = {
  devServer: {
    // host: "localhost",
    host: "0.0.0.0",
    // port: 8080,
    https: false,
    hotOnly: false,
    proxy: {
      "/ahao": {
        target: "http://www.ahaoboy.cn:7777/",
        changeOrigin: true,
        ws: true,
        pathRewrite: {
          "^/ahao": ""
        }
      }
    }
  }
};

App.vue

使用http导出的axios, 访问资源, 此时会出现loading和出错信息

<template>
  <div id="app">
    <button @click="suc">suc</button>
    <button @click="err">err</button>
  </div>
</template>

<script>
import http from "./http";
export default {
  name: "app",
  methods: {
    async suc() {
      let res = await http.get("/ahao/show_all_card");
      console.log(res);
    },
    err() {
      http.get("/ahao/aaaa");
    }
  }
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值