就是先封装axios成一个工具类,然后axios默认是不允许跨域的,得配置一下,最后在发起请求到收到响应可以选择性的调用element-plus loading,使页面交互更契合,然后有些接口在返回时可能检测到未登录,所以在axios封装工具类中,应该用路由转跳到登录或首页

main.js如下

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import http from '@/http'
const app = createApp(App)
app.use(router)
app.use(ElementPlus)
let lsy=app.mount('#app')
http.setMyLoading(lsy.$loading)
http.setRouter(lsy.$router)

这里是lsy而不是app,因为app现在还不是vue实例

新建http.js工具文件

http.js如下

import axios from 'axios'

import qs from 'qs' //qs 是一个增加了一些安全性的查询字符串解析和序列化字符串的库
axios.defaults.withCredentials=true; //请求携带cookie 


var MyLoading=null;
var MyRouter=null;
var baseURL='/api';
const instance = axios.create({
    baseURL
  })


let interceptorsRequest=function(config){
    config.headers['token'] =null;
    return config;
}
// 在发送请求之前带上一些东西,config是请求的配置对象,如果直接返回就等于什么都不带
   
instance.interceptors.request.use(interceptorsRequest)



//用创建的axios实例生成请求拦截器
let interceptorsResponse=function(response){
    if(response.data.code==401){
        console.log(this.MyRouter)
        console.log("需要登录");
        return;
    }
    return response;
}
instance.interceptors.response.use(interceptorsResponse)

let myAxios=function(method,url,params,isLoading=false){
    let tempLoad=null;
    if(isLoading){tempLoad=this.MyLoading}else{
        tempLoad=function(){return null}
    }
    if(method=="post"||method=='Post'||method=='POST'){params=qs.stringify(params)}
    let resolveAndReject=function(resolve,reject){
        let success=function(response){return resolve(response.data)}
        let error=function(error){return reject(error)}
        let object={method:method,url,data:params}
        let option={lock: true,text: '加载中',background: 'rgba(0, 0, 0, 0.7)'}
        let loading=tempLoad(option)
        instance(object,{withCredentials:true}).then(success).catch(error)
        if(loading){loading.close();}
    }
    return new Promise(resolveAndReject);
     //Promise构造函数接收一个函数作为参数,该参数的两个参数是resolve,reject,
     //它们由javaScript引擎提供,其中resolve函数的作用是当Promise对象转移成功,调用resolve并将操作结果作为参数传递出去
     //reject函数的作用是单Promise对象的状态变成为失败时,将操作报出的错误作为其参数传递出去
 }


 let setMyLoading=function(value){
    this.MyLoading=value;
 }
 
 let setRouter=function(value){
     this.MyRouter=value;
 }

 export default{myAxios,setMyLoading,setRouter}


然后负责每个具体请求的js工具类
如其中一个request.js

request.js如下

import http from '@/http'


let token=localStorage.getItem('token')

const post=function(url,data){
   return http.myAxios("post",url,data)
}

const get=function(url,data){
    return http.myAxios("get",url,data)
}

let test=function(path,data){
  return post(path,data)
}
//接口导出
export {test}

配置一下代理跨域

在vue.config.js中修改

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  productionSourceMap: false ,// 打包时不会生成.map文件,加快打包速度
  lintOnSave: false,//将leslint检测机制关闭即可 
  devServer: {
    proxy: {//https://www.jianshu.com/p/ca7d5918cebe
        '/api': {
            // 此处的写法,目的是为了 把上面  /api 替换成 http://127.0.0.1:3000/
            // 如果使用的是自己封装的请求函数 那么你应该这样写 baseURL: '',
            // 注意这里的 api 是必须的,因为是有代理的缘故
            target: 'http://localhost:8081',
            // 允许跨域
            changeOrigin: true,
            ws: true,
            pathRewrite: {'^/api': ''}
        }
    }
  }
})

proxy:{}对象是我添加的

最后调用

<template>
    <el-button type="primary" v-on:click="myclick">点击弹框</el-button>
</template>
<script >
import {test} from '@/request'
export default {
    name: 'MyView',
    methods: {
      myclick(){         
            let mysuccess=function(res){console.log("返回的数据",res)}
            test('/lsy',null).then(mysuccess);
        }
}
}
</script>
<style scoped>

</style>

打完收工

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐