Vue中路由守卫的详细用法
路由守卫
vue-router
提供的导航守卫主要是用来通过跳转或取消的方式守卫导航。有多种机会植入路由导航过程中:全局,单个路由独享,或者组件级
全局守卫
1 2 3 4 5 6
| router.beforeEach((to,from,next) => { })
|
范例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| const routes=[ { path: '/', component: component: () => import('@/views/home.vue'), meta: { auth: true } }, { path: '/login', component: component: () => import('@/views/login.vue'), } ]
......
router.beforeEach((to,from,next) => { if(to.meta.auth){ if(window.isLogin){ next() }else{ next('/login?redirect='+to.fullPath) } } else{ next() } })
|
单个路由守卫
范例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const routes=[ { path: '/', component: component: () => import('@/views/home.vue'), meta: { auth: true }, beforeEnter(to,from,next){ if(window.isLogin){ next() }else{ next('/login?redirect='+to.fullPath) } } ]
|
组件内守卫
可以在路由组件内直接定义以下导航守卫
- beforeRouteEnter
- beforeRouteUpdate
- beforeRouteLeave
范例
1 2 3 4 5 6 7 8 9 10
| mounted(){...}, methods:{...}, beforeRouteEnter(to,from,next){ if(window.isLogin){ next() }else{ next('/login?redirect='+to.fullPath) } }
|
动态路由
通过router.addRoutes(routes)方式动态添加路由
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| router.beforeEach((to, from, next) => { if (window.isLogin) { if (to.path === '/login') { next('/') } else { next() } } else { if (to.path === '/login') { next() } else { next('/login?redirect=' + to.fullPath) } } })
|
1 2 3 4 5 6 7 8 9 10 11
| login() { window.isLogin = true; this.$router.addRoutes([ { path: "/about", } ]); const redirect = this.$route.query.redirect || "/"; this.$router.push(redirect); }
|