溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

基于vue+element實現全局loading過程的案例分析

發布時間:2020-07-11 10:47:31 來源:億速云 閱讀:498 作者:清晨 欄目:開發技術

這篇文章主要介紹基于vue+element實現全局loading過程的案例分析,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

項目中使用的是vue+element實現的全局loading

1.引入所需組件,這里主要就是router和element組件,element組件引入可以參考element官網

2.下面就是重點及代碼實現了

首先是全局的一個變量配置參數,代碼如下:

//全局頁面跳轉是否啟用loading
export const routerLoading = true;

//全局api接口調用是否啟用loading
export const apiLoading = true;

//loading參數配置
export const loadingConfig = {
 lock: true,
 text: 'Loading',
 spinner: 'el-icon-loading',
 background: 'rgba(0, 0, 0, 0.7)'
}

接下來是全局的一個loading簡單封裝,代碼如下

import ElementUI from 'element-ui';
import {loadingConfig} from '../src/config/index' //全局的一個基本參數配置

var loading = null ;
const loadingShow = () => {
 loading = ElementUI.Loading.service(loadingConfig);
}

const loadingHide = () => {
 loading.close();
}

const loadingObj={
 loadingShow,
 loadingHide
}

export default loadingObj

頁面跳轉時全局配置loading,代碼如下:

main.js中添加代碼:

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

import glo_loading from '../loading/index' //loading組件的簡單封裝
import {routerLoading} from '../src/config/index' //全局的頁面跳轉loading是否啟用

Vue.use(ElementUI);

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
 el: '#app',
 router,
 components: { App },
 template: '<App/>'
})

//從后臺獲取的用戶角色
const role = 'user'
//當進入一個頁面是會觸發導航守衛 router.beforeEach 事件
router.beforeEach((to,from,next) => {
 routerLoading &#63; glo_loading.loadingShow() : '' //如果全局啟用頁面跳轉則加載loading
 if(to.meta.roles){
  if(to.meta.roles.includes(role)){
   next() //放行
  }else{
   next({path:"/404"}) //跳到404頁面
  }
 }else{
  next() //放行
 }
routerLoading &#63; glo_loading.loadingHide() : ''//關閉loading層
})

在ajax請求的時候調用全局loading,代碼如下:

// 添加請求攔截器
service.interceptors.request.use(function (config) {
 // 在發送請求之前做些什么
 apiLoading &#63; glo_loading.loadingShow() : ''//全局loading是否啟用
 return config;
}, function (error) {
 // 對請求錯誤做些什么
 console.log(error);
 return Promise.reject(error);
});

// 添加響應攔截器
service.interceptors.response.use(function (response) {
 // 對響應數據做點什么
 if(response.status == 200){
   return response.data;
 }else{
  Promise.reject();
 }
}, function (error) {
 // 對響應錯誤做點什么
 console.log(error);
 apiLoading &#63; glo_loading.loadingHide() : ''
 return Promise.reject(error);
});

以上是基于vue+element實現全局loading過程的案例分析的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女