就是先封装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'
axios.defaults.withCredentials=true;
var MyLoading=null;
var MyRouter=null;
var baseURL='/api';
const instance = axios.create({
baseURL
})
let interceptorsRequest=function(config){
config.headers['token'] =null;
return config;
}
instance.interceptors.request.use(interceptorsRequest)
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);
}
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 ,
lintOnSave: false,
devServer: {
proxy: {
'/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>
打完收工
|