Vue使用NProgress
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
NProgress.configure({ showSpinner: false })
const whiteList = ['/login', '/auth-redirect', '/bind', '/register']
router.beforeEach((to, from, next) => {
NProgress.start()
if (getToken()) {
/* has token*/
if (to.path === '/login') {
next({ path: '/' })
NProgress.done()
} else {
if (store.getters.roles.length === 0) {
// 判斷當前用戶是否已拉取完user_info信息
store.dispatch('GetUserInfo').then(res => {
// 拉取user_info
const roles = res.data.roles
store.dispatch('GenerateRoutes', { roles }).then(accessRoutes => {
// 根據roles權限生成可訪問的路由表
router.addRoutes(accessRoutes) // 動態添加可訪問路由表
next({ ...to, replace: true }) // hack方法 確保addRoutes已完成
})
})
.catch(err => {
store.dispatch('FedLogOut').then(() => {
Message.error(err)
next({ path: '/' })
})
})
} else {
next()
// 沒有動態改變權限的需求可直接next() 刪除下方權限判斷 ↓
// if (hasPermission(store.getters.roles, to.meta.roles)) {
// next()
// } else {
// next({ path: '/401', replace: true, query: { noGoBack: true }})
// }
// 可刪 ↑
}
}
} else {
// 沒有token
if (whiteList.indexOf(to.path) !== -1) {
// 在免登錄白名單,直接進入
next()
} else {
next(`/login?redirect=${to.path}`) // 否則全部重定向到登錄頁
NProgress.done()
}
}
})
router.afterEach(() => {
NProgress.done()
})
directive
Vue 也允許註冊自定義指令。代碼複用和抽象的主要形式是組件。然而,有的情況下,你仍然需要對普通 DOM 元素進行底層操作,這時候就會用到自定義指令。舉個聚焦輸入框的例子,如下:
當頁面加載時,該元素將獲得焦點 (注意:autofocus 在移動版 Safari 上不工作)。事實上,只要你在打開這個頁面後還沒點擊過任何內容,這個輸入框就應當還是處於聚焦狀態。現在讓我們用指令來實現這個功能:
// 註冊一個全局自定義指令 `v-focus`
Vue.directive('focus', {
// 當被綁定的元素插入到 DOM 中時……
inserted: function (el) {
// 聚焦元素
el.focus()
}
})
如果想註冊局部指令,組件中也接受一個 directives 的選項:
directives: {
focus: {
// 指令的定義
inserted: function (el) {
el.focus()
}
}
}
鉤子函數
一個指令定義對象可以提供如下幾個鉤子函數 (均爲可選):
bind
:只調用一次,指令第一次綁定到元素時調用。在這裏可以進行一次性的初始化設置。
inserted
:被綁定元素插入父節點時調用 (僅保證父節點存在,但不一定已被插入文檔中)。
update
:所在組件的 VNode 更新時調用,但是可能發生在其子 VNode 更新之前。指令的值可能發生了改變,也可能沒有。但是你可以通過比較更新前後的值來忽略不必要的模板更新 (詳細的鉤子函數參數見下)。
componentUpdated
:指令所在組件的 VNode 及其子 VNode 全部更新後調用。
unbind
:只調用一次,指令與元素解綁時調用。