项目中经常碰到一些接口不需要加载中的loading动画 比如收藏和取消收藏 所以做了一个axios的简单封装
1.项目src下新建request文件夹 里面新建api.js和request.js
request.js
//request.js
import axios from 'axios'
import { Toast } from 'vant'
// 创建axios实例 需要loading加载
const request = axios.create({
baseURL: "https://接口地址",
timeout: 100000 // 请求超时时间
})
//不需要loading加载
const requestloading = axios.create({
baseURL: "https://接口地址",
timeout: 100000 // 请求超时时间
})
function startLoading() {
// 开始加载
Toast.loading({
message: '加载中...',
forbidClick: true,
});
}
function endLoading() {
// 结束加载
Toast.clear()
}
// 添加request拦截器 加载loading
requestloading.interceptors.request.use(config => {
startLoading()
return config
}, error => {
Promise.reject(error)
})
// 添加respone拦截器 加载loading
requestloading.interceptors.response.use(
response => {
endLoading()
return Promise.resolve(response.data)
},
error => {
startLoading()
if (error.response) {
switch (error.response.status) {
case 401:
console.log(401)
break;
case 403:
console.log(403)
break;
case 404:
Toast({
message: '网络请求不存在',
duration: 1500,
forbidClick: true
})
console.log(404)
break;
case 500:
console.log(500)
break;
}
}
return Promise.reject(error.response)
}
)
// 添加request拦截器 不加载loading
request.interceptors.request.use(config => {
return config
}, error => {
Promise.reject(error)
})
// 添加respone拦截器 不加载loading
request.interceptors.response.use(
response => {
return Promise.resolve(response.data)
},
error => {
startLoading()
if (error.response) {
switch (error.response.status) {
case 401:
console.log(401)
break;
case 403:
console.log(403)
break;
case 404:
Toast({
message: '网络请求不存在',
duration: 1500,
forbidClick: true
})
console.log(404)
break;
case 500:
console.log(500)
break;
}
}
return Promise.reject(error.response)
}
)
// export default request
export let req = request
export let reqloading = requestloading
api.js
// api.js
import {req,reqloading} from './request'
export function getuserInfo(obj) {
return req({ //不需要loading加载
url: '/List.php',
method: 'get',
params: obj, //根据需求data或params
})
}
export function getuserInfos(obj) {
return reqloading({ //需要loading加载
url: '/List.php',
method: 'get',
params: obj,
})
}
页面中使用home.vue
//home.vue
<template>
<div>
<div @click="btnloading">btnloading</div>
<div @click="btn">btn</div>
</div>
</template>
<script>
import { getuserInfos , getuserInfo } from "@/request/api.js"
export default {
name: '',
data() {
return {
}
},
methods:{
async btn(){
var params = {
id: 1
}
await getuserInfo(params).then((res) => {
console.log(res.data)
})
},
async btnloading(){
var params = {
id: 3
}
await getuserInfos(params).then((res) => {
console.log(res.data)
})
}
},
}
</script>
wx:sww355000