之前寫過關於全局配置http攔截器的隨筆,現在有個需求,在微信支付時,生成二維碼,頁面顯示一個遮罩層,二維碼頁面需要每兩秒請求一次接口,若返回結果為已支付,則進行頁面跳轉,但因為全局http中loading的存在,每兩秒遮罩會閃動一次,所以此處需要配置不顯示loading。
解決思路是:
1.全局聲明了一個變量isShowLoading: true;
2.全局的http.js引入聲明全局變量的js文件,並在http攔截器中判斷isShowLoading是否為true,如果是,則加載loading
3.在main.js中引入聲明全局變量的js文件,並在生成二維碼的頁面將isShowLoading賦值為false,當用戶關閉二維碼或支付成功后跳轉頁面時,將isShowLoading再賦值為true,完成
相關代碼:(紅色為重點代碼)
1.http.js中相關代碼
import Axios from 'axios' import router from './router' import { Loading, Message, MessageBox } from 'element-ui' import common from './assets/js/common'//引用模塊進來 // 超時時間 Axios.defaults.timeout = 5000 Axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; Axios.defaults.withCredentials = true Axios.defaults.baseURL = "https://www.chaopengjiankang.com/api" // http請求攔截器 var loadinginstace Axios.interceptors.request.use(config => { config.headers = { 'Content-Type': 'application/json' } // element ui Loading方法 if(common.isShowLoading == true){ loadinginstace = Loading.service({ fullscreen: true }) } return config }, error => { loadinginstace.close(); Message.error({ message: '網絡不給力,請稍后再試' }) return Promise.reject(error) })
2.main.js中全局引入
import Common from './assets/js/common' Vue.prototype.common = Common;
3.局部組件中修改狀態值
//打開微信支付頁面 if(index == 0){ this.$axios.post("/wxPay/unifiedorder",{ "orderId": this.orderId }).then((response) => { let res = response.data; if(res.code == 0){ this.$refs.wx_mask.style.display = 'block'; this.wxUrl = res.data; this.qrcode();//繪制二維碼 this.common.isShowLoading = false;//打開二維碼,且未支付時關閉http攔截的loading //判斷是否支付,進行跳轉 var count_downtimer = setInterval(()=>{ this.$axios.post("/wxPay/checkOrderIsPay",{ "orderId":this.orderId }) .then((response) => { this.common.isShowLoading = false; let res = response.data; if(res.code == 0) { //支付成功 if(res.data == 1){ this.$router.push({name: 'paySuccess'}); clearInterval(count_downtimer); this.common.isShowLoading = true;//開啟http攔截的loading }
//手動關閉二維碼 if(this.$refs.wx_mask.style.display == 'none'){ clearInterval(count_downtimer); this.common.isShowLoading = true;//關掉二維碼后重新開始進行http攔截,顯示loading } }else{ this.$layer.msg(res.msg); } }).catch((err) => { console.log(err); }) }, 2000); } }).catch((err) =>{ console.log("微信支付失敗",err); })
這個方法看起來有點麻煩,不過效果實現了。希望以后能找到簡便的方式