Post请求Loading及封装
1.组件
-
axios
-
sweetalert
2.目标
对post请求进行封装的目标及最终实现如下:
-
实现在请求时弹出遮罩层
-
在header中设置Authorization
-
发生错误弹出错误提示信息
-
鉴权失败后跳转到登录页面
3.loading代码
使用 JS 代码实现在页面上显示遮罩层及图片,代码如下:
/* * GUID */ function guid () { function S4 () { return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1) } return (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4()) } /* * 显示loading遮罩层 */ function loading () { var id = guid() var maskBg = document.createElement('div') maskBg.id = 'mask_bg_' + id maskBg.style.position = 'absolute' maskBg.style.top = '0px' maskBg.style.left = '0px' maskBg.style.width = '100%' maskBg.style.height = '100%' maskBg.style.backgroundColor = '#777' maskBg.style.opacity = 0.6 maskBg.style.zIndex = 10001 document.body.appendChild(maskBg) var maskMsg = document.createElement('div') maskMsg.style.position = 'absolute' maskMsg.style.top = '43%' maskMsg.style.left = '43%' maskMsg.style.textAlign = 'center' maskMsg.style.zIndex = 10002 var image = document.createElement('img') image.src = '/images/rotate_loader.svg' // 加载图片 maskMsg.appendChild(image) maskBg.appendChild(maskMsg) return maskBg.id } /* * 关闭遮罩层 */ function loaded (id) { var maskBg = document.getElementById(id) if (maskBg != null) { maskBg.parentNode.removeChild(maskBg) } } export {loading, loaded}
4.post请求封装
代码如下:
import axios from 'axios' import swal from 'sweetalert' import {loading, loaded} from './loading' const config = { baseURL: '', timeout: 60000, headers: { 'Content-Type': 'application/json' }, responseType: 'json' } const postRequest = (url, data) => { let _id = loading() // eslint-disable-next-line const promise = new Promise((resolve, reject) => { // 设置Headers的Authorization,鉴权Token config.headers['Authorization'] = localStorage.getItem('token_type') + ' ' + localStorage.getItem('access_token') axios.post( url, data, config ).then((response) => { loaded(_id) resolve(response) }).catch((error) => { loaded(_id) console.log(error) let status = error.response.status swal(status.toString(), error.message, 'error') if (status === 401) { swal({ title: '鉴权失败', text: error.message, icon: 'error', button: "确定", }).then((value) => { console.log(value) // 路由跳转 }) } // reject(error) }) }) return promise }
5.Vue中使用
import {postRequest} from "@/assets/utils/utils" let _this = this postRequest( 'url', // url data // Object ).then((response) => { ...... })