vue cli3请求封装(结合vant ui 配置项目提示,赞!)

src文件夹下新建tools工具文件夹
新建如下js文件:
baseURL.js(分环境设置请求基准地址)
https.js(请求封装)
mixin.js(配置提示信息等公共方法)

baseURL.js(分环境设置基准地址详细步骤:https://blog.csdn.net/qq_46003166/article/details/103906287)

https.js(结合实际后台约定 进行配置)

import axios from "axios";
import baseUrl from "./setBaseUrl";
const Qs = require('qs');
const instance = axios.create({
  timeout: 15000,
  baseURL: baseUrl,
  responseType: 'json',
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
  },
  transformRequest: [
    function(data) {
      data = Qs.stringify(data);
      return data;
    }
  ]
});

// Add a request interceptor
instance.interceptors.request.use(
  config => {
    // // 添加请求头
    console.log(config)
    // let postData = config.data;
    // console.log(postData);
    return config;
  },
  error => {
    // Do something with request error
    return Promise.reject(error);
  }
);
// Add a response interceptor
instance.interceptors.response.use(
  res => {
    console.log(res)
    // let resultData = res.data;
    // console.log(resultData);
    // return resultData
    // if (resultData.code == 200 || resultData.code == 201 || resultData.code == 203) {
    //   return resultData.data;
    // } else {
    //   let msg = resultData.msg ? resultData.msg : "系统出小差了";
    //   return Promise.reject(msg);
    // }
  },
  error => {
    // Do something with response error
    return Promise.reject("系统出小差了");
  }
);

export default instance;

mixin.js(重点来咯~)
this.showToast(0, “普通提示框”);
this.showToast(1, “成功提示框”);
可以根据实际情况在里面增减
成功与否在created里面验证一下再使用哟

export default {
    data() {
        return {
            httpFlag: false, // 请求标识,避免重复请求
        }
    },
    beforeDestroy() { //在组件生命周期结束的时候销毁。
        this.httpFlag = false;
        this.hideLoading(); 
    },
    destroyed() {
        this.httpFlag = false;
        this.hideLoading(); 
    },
    methods: {
        // 检查id 是否存在
        checkId(id) {
            if (!id) {
                this.$router.push({
                    path: '/error',
                    query: { 'errinfo': encodeURIComponent('id不存在') }
                })
            }
        },
        // 显示Loading效果
        showLoading(info) {
            info = info ? info : '加载中...'
            this.$toast.loading(info);
        },
        // 清空提示框
        hideLoading() {
            this.$toast.clear();
        },
        showToast(type, text) {
            try {
                type === 1 ? this.$toast.success(text) : this.$toast(text);
                // type === 1 ? this.$toast.success(text) : type === 2 ? this.$toast.fail(text) : this.$toast(text);
            } catch (error) {
                throw '参数错误'
            }
        },
    },
}

温馨提示:
vant ui (https://youzan.github.io/vant/?source=vuejsorg#/zh-CN/quickstart)
请按照官网快速上手进行引入,在main.js里面配置如下:

import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import baseUrl from "./tools/setBaseUrl"; // 引入分环境设置url
import instance from "@/tools/https";  // 引入封装请求
import axios from "axios";
import { Step, Steps, Overlay, Toast, CountDown } from "vant";

// 提示语配置
Toast.setDefaultOptions("loading", {
  forbidClick: true, // 禁止背景点击
  loadingType: "spinner", // 加载图
  duration: 0, // 关闭时长ms,0 默认不关闭
  mask: false, // 是否遮罩
});
Toast.setDefaultOptions("success", {
  forbidClick: true,
  duration: 1000, // 关闭时长ms,0 默认不关闭
});
Toast.setDefaultOptions("fail", {
  forbidClick: true,
  duration: 1000, // 关闭时长ms,0 默认不关闭
});
Vue.use(Step)
  .use(Steps)
  .use(Overlay)
  .use(Toast)
  .use(CountDown);

Vue.prototype.$axios = instance;
axios.defaults.baseURL = baseUrl;

Vue.config.productionTip = false;

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount("#app");

最后,在项目中使用,如下:
以index.vue为例

<template>
  <div class="index">
    
  </div>
</template>

<script>
import mixin from "@/tools/mixin";

export default {
  name: "index",
  data() {
    return {
      testId : '',
    };
  },
  mixins: [mixin],
  created() {
    console.log(this.$route.params.testId, '获取其他页面传递过来的id')
    this.testId = this.$route.params.testId;
    this.checkId(this.testId);
    this.brandData(); // 检查id是否存在 再调用
  },
  methods: {
    async testData() {
      if (this.httpFlag) {
        return;
      }
      this.httpFlag = true;
      this.showLoading();
      try {
        let postData = {
         		// 这里是请求参数
        };
        let resData = await this.$axios.post("这里是接口地址", postData);
        console.log(resData);
        // 这里是请求成功后的逻辑处理
        this.hideLoading();
      } catch (error) {
        console.log(error);
        this.showToast(0, error);
      }
      this.httpFlag = false;
    },
    async testGet() {
      if (this.httpFlag) {
        return;
      }
      this.httpFlag = true;
      this.showLoading();
      try {
        let getData = {
         		// 这里是请求参数
        };
        let resData = await this.$axios.get("这里是接口地址", {
				params: getData
		});
        console.log(resData);
        // 这里是请求成功后的逻辑处理
        this.hideLoading();
      } catch (error) {
        console.log(error);
        this.showToast(0, error);
      }
      this.httpFlag = false;
    },
  }
};
</script>

router文件下:
/error文件内容可以私聊我哟,内容有点多不好粘贴…

import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: "/index",
  },
  {
    path: "/error",
    name: "error",
    meta: {
      title: "💤系统错误",
    },
    component: () => import("@/pages/error/error"),
  },
  {
    path: "/index",
    name: "index",
    meta: { title: "首页" },
    component: () => import("@/pages/index/index"),
  }
];

const router = new VueRouter({
  routes,
});

router.beforeEach((to, from, next) => {
  if (to.matched.length === 0) {
    next({
      path: "/error",
      query: { errinfo: encodeURIComponent("迷路了") },
    });
  }
  /* 路由发生变化修改页面title */
  if (to.meta.title) {
    document.title = to.meta.title;
  }
  next();
});

export default router;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值