基于vue+element實現(xiàn)全局loading過程詳解
項目中使用的是vue+element實現(xiàn)的全局loading
1.引入所需組件,這里主要就是router和element組件,element組件引入可以參考element官網(wǎng)
2.下面就是重點及代碼實現(xiàn)了
首先是全局的一個變量配置參數(shù),代碼如下:
//全局頁面跳轉(zhuǎn)是否啟用loading export const routerLoading = true; //全局api接口調(diào)用是否啟用loading export const apiLoading = true; //loading參數(shù)配置 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' //全局的一個基本參數(shù)配置 var loading = null ; const loadingShow = () => { loading = ElementUI.Loading.service(loadingConfig); } const loadingHide = () => { loading.close(); } const loadingObj={ loadingShow, loadingHide } export default loadingObj
頁面跳轉(zhuǎn)時全局配置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' //全局的頁面跳轉(zhuǎn)loading是否啟用 Vue.use(ElementUI); Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, components: { App }, template: '<App/>' }) //從后臺獲取的用戶角色 const role = 'user' //當(dāng)進(jìn)入一個頁面是會觸發(fā)導(dǎo)航守衛(wèi) router.beforeEach 事件 router.beforeEach((to,from,next) => { routerLoading ? glo_loading.loadingShow() : '' //如果全局啟用頁面跳轉(zhuǎn)則加載loading if(to.meta.roles){ if(to.meta.roles.includes(role)){ next() //放行 }else{ next({path:"/404"}) //跳到404頁面 } }else{ next() //放行 } routerLoading ? glo_loading.loadingHide() : ''//關(guān)閉loading層 })
在ajax請求的時候調(diào)用全局loading,代碼如下:
// 添加請求攔截器 service.interceptors.request.use(function (config) { // 在發(fā)送請求之前做些什么 apiLoading ? glo_loading.loadingShow() : ''//全局loading是否啟用 return config; }, function (error) { // 對請求錯誤做些什么 console.log(error); return Promise.reject(error); }); // 添加響應(yīng)攔截器 service.interceptors.response.use(function (response) { // 對響應(yīng)數(shù)據(jù)做點什么 if(response.status == 200){ return response.data; }else{ Promise.reject(); } }, function (error) { // 對響應(yīng)錯誤做點什么 console.log(error); apiLoading ? glo_loading.loadingHide() : '' return Promise.reject(error); });
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vue路由對不同界面進(jìn)行傳參及跳轉(zhuǎn)的總結(jié)
這篇文章主要介紹了vue路由對不同界面進(jìn)行傳參及跳轉(zhuǎn)的總結(jié),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04Vue數(shù)據(jù)驅(qū)動模擬實現(xiàn)2
這篇文章主要介紹了Vue數(shù)據(jù)驅(qū)動模擬實現(xiàn)的相關(guān)資料,實現(xiàn)Observer構(gòu)造函數(shù),監(jiān)聽已有數(shù)據(jù)data中的所有屬性,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-01-01