vue-router之路由钩子(八)
路由鉤子,即導(dǎo)航鉤子,其實(shí)就是路由攔截器,vue-router一共有三類:
全局鉤子:最常用
路由單獨(dú)鉤子
組件內(nèi)鉤子
1、全局鉤子
在src/router/index.js中使用,代碼如下:
//?定義路由配置const?router?=?new?VueRouter({?...?})//?全局路由攔截-進(jìn)入頁(yè)面前執(zhí)行router.beforeEach((to,?from,?next)?=>?{//?這里可以加入全局登陸判斷//?繼續(xù)執(zhí)行next();});//?全局后置鉤子-常用于結(jié)束動(dòng)畫等router.afterEach(()?=>?{//不接受next});export?default?router;每個(gè)鉤子方法接收三個(gè)參數(shù):
to: Route : 即將要進(jìn)入的目標(biāo) [路由對(duì)象]
from: Route : 當(dāng)前導(dǎo)航正要離開的路由
next: Function : 繼續(xù)執(zhí)行函數(shù)
next():繼續(xù)執(zhí)行
next(false):中斷當(dāng)前的導(dǎo)航。
next(‘/‘) 或 next({ path: ‘/‘ }):跳轉(zhuǎn)新頁(yè)面,常用于登陸失效跳轉(zhuǎn)登陸
2、路由單獨(dú)鉤子
使用:在路由配置中單獨(dú)加入鉤子,在src/router/index.js中使用,代碼如下:
{path:'/home/one',?//?子頁(yè)面1component:?One,//?路由內(nèi)鉤子beforeEnter:?(to,?from,?next)?=>?{console.log('進(jìn)入前執(zhí)行');next();}}3、組件內(nèi)鉤子
使用:在路由組件內(nèi)定義鉤子函數(shù):
beforeRouteEnter:進(jìn)入頁(yè)面前調(diào)用
beforeRouteUpdate (2.2 新增):頁(yè)面路由改變時(shí)調(diào)用,一般需要帶參數(shù)
beforeRouteLeave:離開頁(yè)面調(diào)用
任意找一頁(yè)面,編寫如下代碼:
<script>export?default?{name:?'Two',data?()?{return?{msg:?'Hi,?I?am?Two?Page!'}},//?進(jìn)入頁(yè)面前調(diào)用beforeRouteEnter(to,?from,?next)?{console.log('進(jìn)入enter路由鉤子')next()},//?離開頁(yè)面調(diào)用beforeRouteLeave(to,from,?next){console.log('進(jìn)入leave路由鉤子')next()},//?頁(yè)面路由改變時(shí)調(diào)用beforeRouteUpdate(to,?from,?next)?{console.log('進(jìn)入update路由鉤子')console.log(to.params.id)next()}}</script>轉(zhuǎn)載于:https://blog.51cto.com/4547985/2390810
總結(jié)
以上是生活随笔為你收集整理的vue-router之路由钩子(八)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 浅析Nginx 正向代理与反向代理
- 下一篇: Vue进阶知识笔记