vue+axios+element ui 实现全局loading加载示例
2019/6/27 7:42:54
本文主要是介绍vue+axios+element ui 实现全局loading加载示例,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
实现全局loading加载
分析需求,我们只需要在请求发起的时候开始loading,响应结束的时候关闭loading,就这么简单 对不对?
import axios from 'axios'; import { Message, Loading } from 'element-ui'; import Cookies from 'js-cookie'; import router from '@/router/index' let loading //定义loading变量 function startLoading() { //使用Element loading-start 方法 loading = Loading.service({ lock: true, text: '加载中……', background: 'rgba(0, 0, 0, 0.7)' }) } function endLoading() { //使用Element loading-close 方法 loading.close() } //那么 showFullScreenLoading() tryHideFullScreenLoading() 要干的事儿就是将同一时刻的请求合并。 //声明一个变量 needLoadingRequestCount,每次调用showFullScreenLoading方法 needLoadingRequestCount + 1。 //调用tryHideFullScreenLoading()方法,needLoadingRequestCount - 1。needLoadingRequestCount为 0 时,结束 loading。 let needLoadingRequestCount = 0 export function showFullScreenLoading() { if (needLoadingRequestCount === 0) { startLoading() } needLoadingRequestCount++ } export function tryHideFullScreenLoading() { if (needLoadingRequestCount <= 0) return needLoadingRequestCount-- if (needLoadingRequestCount === 0) { endLoading() } } //http request 拦截器 axios.interceptors.request.use( config => { var token = '' if(typeof Cookies.get('user') === 'undefined'){ //此时为空 }else { token = JSON.parse(Cookies.get('user')).token }//注意使用的时候需要引入cookie方法,推荐js-cookie config.data = JSON.stringify(config.data); config.headers = { 'Content-Type':'application/json' } if(token != ''){ config.headers.token = token; } showFullScreenLoading() return config; }, error => { return Promise.reject(err); } ); //http response 拦截器 axios.interceptors.response.use( response => { //当返回信息为未登录或者登录失效的时候重定向为登录页面 if(response.data.code == 'W_100004' || response.data.message == '用户未登录或登录超时,请登录!'){ router.push({ path:"/", querry:{redirect:router.currentRoute.fullPath}//从哪个页面跳转 }) } tryHideFullScreenLoading() return response; }, error => { return Promise.reject(error) } )
以上这篇vue+axios+element ui 实现全局loading加载示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持找一找教程网。
这篇关于vue+axios+element ui 实现全局loading加载示例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-04package.json 文件位置在哪?-icode9专业技术文章分享
- 2024-10-01Craco.js学习:从入门到实践指南
- 2024-10-01Create-React-App学习:入门与实践指南
- 2024-10-01CSS-in-JS学习:从入门到实践指南
- 2024-09-30JSX语法学习:从入门到初步掌握
- 2024-09-30Mock.js学习:入门教程与实战演练
- 2024-09-30React Hooks学习:从入门到实践
- 2024-09-30受控组件学习:React中的基础入门教程
- 2024-09-29JS定时器教程:初学者必看指南
- 2024-09-29JS对象教程:初学者的全面指南