1.项目目录
2.index.js
import axios from 'axios' import router from '../router/index' import { ElLoading, ElMessage } from 'element-plus' import config from '~/config'axios.defaults.baseURL = config[import.meta.env.MODE].baseUrl // config.js 里面控制 axios.defaults.withCredentials = false
let loadingInstance = null let loadingCount = 0 // axios.defaults.timeout = 20000; axios.interceptors.request.use(config => { if (loadingCount === 0) { loadingInstance = ElLoading.service({ lock: true, spinner: 'custom', text: '数据加载中,请稍后...', background: 'rgba(0, 0, 0, 0.3)' }) } loadingCount++ if (localStorage.getItem('token')) { config.headers.Authorization = localStorage.getItem('token') config.headers.token = localStorage.getItem('token') config.headers['Content-Type'] = 'application/json' } return config })
axios.interceptors.response.use(response => { loadingCount-- if (loadingInstance && loadingCount === 0) { loadingInstance.close() } if (response.data.code && response.data.code !== '200') { if (response.data.code === '401') { localStorage.removeItem('userinfo') localStorage.removeItem('token') localStorage.removeItem('selectedSId') localStorage.removeItem('selectedRId') localStorage.removeItem('selectedSName') localStorage.removeItem('selectedRName') router.push('/Login') } else if (response.data.code === '888') { ElMessage.error(response.data.msg) // router.push('/Login') } else if (response.data.code === '900') { // ElementUI.ElMessage.error(response.data.msg) router.push('/Login') } } return response }, (err) => { console.log(err) loadingCount-- if (loadingInstance && loadingCount === 0) { loadingInstance.close() } })
export default axios 3.统一接口配置文件api.js
4.main.js
import { createApp } from 'vue' import api from './server/api' const app = createApp(App) app.config.globalProperties.$http = api 5.页面中使用 引入 import { reactive, ref, toRefs , onMounted, getCurrentInstance } from 'vue' // 请求 const globalProperties = getCurrentInstance().appContext.config.globalProperties const http = globalProperties.$http const getImgCaptcha = async ()=>{ const {data:resData} = await http.getImgCaptcha() if (resData.code !== '200') return ElMessage.error(resData.msg) state.loginForm.imgToken = resData.data.authCodeToken state.url = resData.data.img } 6.ps:检查项目中千万不要引入两个axios,嘿嘿