vue Nprogress進度條功能實現常見問題
阿新 • • 發佈:2021-07-28
NProgress是頁面跳轉是出現在瀏覽器頂部的進度條
官網:http://ricostacruz.com/nprogress/
:https://github.com/rstacruz/nprogress
下圖中的這種頂部進度條是非常常見的,在專案中有對應的外掛。
Nprogress
Nprogress
進度條的使用方法如下:
1.安裝nprogress
外掛
npm install --save nprogress
注意此處的--save
等同於-s
,就是將外掛的名稱及版本號儲存到package.on
檔案中的dependencies
中,這樣其他人克隆專案後,可以通過npm install
就可以下載下來所有的外掛到node_modules
2.nprogress
外掛的使用
此處進度條主要用於頁面路由的跳轉過程中,因此可以直接在router/index.js
中使用:
在路由跳轉之前,開啟進度條載入,在路由跳轉之後,結束進度條的載入。
router/index.js
檔案內容如下:
import Vue from "vue"; import VueRouter from "vue-router"; import store from "@/store"; import HomeLayout form "@/views/home/layout"; import NProgress from "nprogress"; import userCenter from "./modules/userCenter"; import 'nprogress/nprogress.' Vue.use(VueRouter); NProgress.inc(0.2); NProgress.configure({easing:'ease',speed:2000,showSpinner:false,trickle:false}) const routes = [{ path:"/",name:"Index",redirect:"/index" },{ path:"/index",name:'Index',component:()=>import ('@/views/home/index.vue'),meta:{title:'首頁'} },{ path:'/home',name:'Home',component:()=>import('@/views/home/main'),{ path:'/login',name:'Login',component:()=>import ('@/views/login'),meta:{title:'登入'} },{ path:'/register',name:'register',component:()=>import('@/views/register'),meta:{title:'註冊'} }http://www.cppcns.com,{ path:'/404',name:'404',component:()=>import('@/views/errorPage') },{ path:'*',redirect:'/404' }] const router = new VueRouter({ mode:'history',routes }) //路由跳轉之前做攔截 router.beforeEach((to,from,next)=>{ //頁面跳轉之前,開啟進度條 NProgress.start(); //某些攔截操作,是否登入許可權等... const token = window.localStorage.getItem('token');//從localstorwww.cppcns.comage中獲取快取 if(to.meta.title){ document.title = to.meta.title;//將瀏覽器選項卡的標題改為頁面的title } store.commit('changeCurrentPage',to.path); const reg = /[a-zA-Z]+\/$/; //不需要校驗的路由直接跳轉 if(!to.meta.requireAuth){ if(reg.test(to.path)){ next(to.path.replace(reg,'')); return; } next(); return } if(token&&to.name!=='Indexwww.cppcns.com'){ //已登入且要跳轉的頁面不是登入頁面 if(reg.test(to.path)){ next(to.path.replace(reg,'')); return; } next();//可以直接跳轉 }else if(token && to.name == 'Index'){ //已登入且要跳轉的頁面是登入頁 if(reg.test(to.path)){ next(to.path.replace(reg,'')); return } next('/home');//直接跳轉到首頁 }else if(!token && to.name !='Index'){ //未登入且要跳轉的頁面不是登入頁 next('/index');//跳轉到登入頁 }else{ if(reg.test(to.path)){ next(to.path.replace(reg,'')); return; } next() } }) router.afterEach(to=>{ NProgress.done(); window.scrollTo(0,0); }) //處理重複點選當前頁選單,出現警告問題 const originalPush = VueRouter.prototype.push; VueRouter.prototype.push = function push(location){ return originalPush.call(this,location).catch(err=>err); } export default router;
上面的重點如下:
引入外掛及對應的css
nprogress
配置引數
3.router.beforeEach
路由跳轉之前攔截時,載入進度條
4.router.afterEach
路由跳轉結束後,關閉進度條
3.nprogress
外掛修改樣式
在App.vue
檔案中的style
樣式中,新增如下程式碼,更改進度條的顏色
#nprogress .bar { background: #f90 !important; QENuNvkJc//自定義顏色 }
到此這篇關於vue Nprogress進度條功能實現的文章就介紹到這了,更多相關vue Nprogress進度條內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!