問題
在使用 Vue.js 開發(fā)項目時,會用到 vue-router 模塊來進(jìn)行路由管理麻捻。為了在用戶訪問每個頁面之前判斷用戶是否有訪問該頁面權(quán)限,需要用到 vue-router 的 beforeEach 全局鉤子呀袱,在這個鉤子中進(jìn)行權(quán)限判斷贸毕,決定允許或拒絕用戶訪問,或者是跳轉(zhuǎn)到登錄界面夜赵。
代碼如下(vue-router 1.0):
Vue.use(Router)
// routing
var router = new Router()
router.map({
'/reject': {
component: RejectView
},
'/login': {
component: LoginView
}
})
router.start(App, '#app')
router.beforeEach(function (transition) {
if ( transition.to.path.indexOf('/login') === 0) {
transition.next()
return
}
if (document.cookie.indexOf('isLogin=true') < 0) {
router.go('/login?redirect=' + transition.to.path)
transition.next()
} else {
var cname = transition.to.params.cname
if (cname !== undefined) {
var has_permission = store.state.userInfo.power[Nav[cname]]
if (!has_permission) {
router.go('/reject')
transition.next()
return
}
}
transition.next()
}
})
然而出現(xiàn)一個bug崖咨,當(dāng)我手動 F5 刷新頁面時,卻沒有觸發(fā) beforeEach 鉤子油吭。
原因
查詢 vue-router1.0 的說明文檔,文檔上的 Basic Usage 代碼如下:
// Load the plugin
Vue.use(VueRouter)
// Define some components
var Foo = {
template: '<p>This is foo!</p>'
}
var Bar = {
template: '<p>This is bar!</p>'
}
// The router needs a root component to render.
// For demo purposes, we will just use an empty one
// because we are using the HTML as the app template.
// !! Note that the App is not a Vue instance.
var App = {}
// Create a router instance.
// You can pass in additional options here, but let's
// keep it simple for now.
var router = new VueRouter()
// Define some routes.
// Each route should map to a component. The "component" can
// either be an actual component constructor created via
// Vue.extend(), or just a component options object.
// We'll talk about nested routes later.
router.map({
'/foo': {
component: Foo
},
'/bar': {
component: Bar
}
})
// Now we can start the app!
// The router will create an instance of App and mount to
// the element matching the selector #app.
router.start(App, '#app')
可以發(fā)現(xiàn)署拟,樣例中把 router.start(App, '#app') 這行代碼放在了最后婉宰。因為這一步是創(chuàng)建和掛載根實例,是啟動路由的最后一步推穷,需要在定義路由實例和配置路由之后進(jìn)行心包。
解決
修改以后的代碼如下:
Vue.use(Router)
// routing
var router = new Router()
router.map({
'/reject': {
component: RejectView
},
'/login': {
component: LoginView
}
})
router.beforeEach(function (transition) {
if ( transition.to.path.indexOf('/login') === 0) {
transition.next()
return
}
if (document.cookie.indexOf('isLogin=true') < 0) {
router.go('/login?redirect=' + transition.to.path)
transition.next()
} else {
var cname = transition.to.params.cname
if (cname !== undefined) {
var has_permission = store.state.userInfo.power[Nav[cname]]
if (!has_permission) {
router.go('/reject')
transition.next()
return
}
}
transition.next()
}
})
router.start(App, '#app')
總結(jié)
在使用 vue-router 模塊時,掛載根實例的步驟要放在最后馒铃,不然會導(dǎo)致配置不成功蟹腾。
參考資料
文章標(biāo)題:解決刷新頁面不觸發(fā) vue-router 的 beforeEach 鉤子的問題
文章作者:Ciel Ni
文章鏈接:http://www.cielni.com/2017/06/30/vue-router-beforeEach/
有問題或建議歡迎在我的博客討論痕惋,轉(zhuǎn)載或引用希望標(biāo)明出處,感激不盡娃殖!