1用含、全局的鉤子
beforeEach(to羊始,from,next)
afterEach(to笙纤,from耗溜,next)
2、組建內(nèi)的導(dǎo)航鉤子
組件內(nèi)的導(dǎo)航鉤子主要有這三種:beforeRouteEnter省容、beforeRouteUpdate抖拴、beforeRouteLeave。他們是直接在路由組件內(nèi)部直接進(jìn)行定義的
methods: {},
beforeRouteLeave (to, from, next) {}
需要注意是:
beforeRouteEnter 不能獲取組件實(shí)例 this,因?yàn)楫?dāng)守衛(wèi)執(zhí)行前阿宅,組件實(shí)例被沒有被創(chuàng)建出來(lái)候衍,剩下兩個(gè)鉤子則可以正常獲取組件實(shí)例 this
beforeRouteEnter獲取到this實(shí)例
beforeRouteEnter (to, from, next) {
next(vm => {
// 通過 `vm` 訪問組件實(shí)例
})
}
最后是完整的導(dǎo)航解析流程:
1、導(dǎo)航被觸發(fā)
2洒放、在失活的組件里調(diào)用離開守衛(wèi)
3蛉鹿、調(diào)用全局的 beforeEach 守衛(wèi)
4、在重用的組件里調(diào)用 beforeRouteUpdate 守衛(wèi)
5往湿、在路由配置里調(diào)用 beforEnter
6妖异、解析異步路由組件
7、在被激活的組件里調(diào)用 beforeRouteEnter
8领追、調(diào)用全局的 beforeResolve 守衛(wèi)
9他膳、導(dǎo)航被確認(rèn)
10、調(diào)用全局的 afterEach 鉤子
11绒窑、觸發(fā) DOM 更新
12棕孙、在創(chuàng)建好的實(shí)例調(diào)用 beforeRouteEnter 守衛(wèi)中傳給 next 的回調(diào)函數(shù)
路由攔截登錄例子
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
const router = new Router({
routes: [
{
path: '/',
/*
* 按需加載
*/
component: (resolve) => {
require(['../components/Home'], resolve)
}
}, {
path: '/record',
name: 'record',
component: (resolve) => {
require(['../components/Record'], resolve)
}
}, {
path: '/Register',
name: 'Register',
component: (resolve) => {
require(['../components/Register'], resolve)
}
}, {
path: '/Luck',
name: 'Luck',
// 需要登錄才能進(jìn)入的頁(yè)面可以增加一個(gè)meta屬性
meta: {
requireAuth: true
},
component: (resolve) => {
require(['../components/luck28/Luck'], resolve)
}
}
]
})
// 判斷是否需要登錄權(quán)限 以及是否登錄
router.beforeEach((to, from, next) => {
if (to.matched.some(res => res.meta.requireAuth)) {// 判斷是否需要登錄權(quán)限
if (localStorage.getItem('username')) {// 判斷是否登錄
next()
} else {// 沒登錄則跳轉(zhuǎn)到登錄界面
next({
path: '/Register',
query: {redirect: to.fullPath}
})
}
} else {
next()
}
})
export default router
當(dāng)router的mode為history時(shí),去掉#
router.beforeEach((route, redirect, next) => {
let title = route.meta.title
document.title = title || ''
console.log(route.hash)
if (route.hash !== '') {
const id = route.hash.replace('#', '')
const element = document.getElementById(id)
if (element) element.scrollIntoView()
}
if (route.path !== '/') {
indexScrollTop = document.body.scrollTop
}
next()
})
router.afterEach((route, redirect) => {
if (route.hash !== '') {
const id = route.hash.replace('#', '')
const element = document.getElementById(id)
if (element) element.scrollIntoView()
}
if (route.path !== '/') {
document.body.scrollTop = 0
} else {
Vue.nextTick(() => {
document.body.scrollTop = indexScrollTop
})
}
})
這樣就做好了登錄攔截.我們只需在main.js中引入router就可以了.