路由 vue-router
路由 vue-route
基本使用
路由 vue-router
基本使用
1 2 3 4 5 6 7 8 9 10
|
router.beforeEach((to, from, next) => { document.title = to.meta.title; next(); });
<div> {{ $route.meta.title}} </div>
|
组件内导航守卫
1 2 3 4 5 6 7 8 9
|
beforeRouteLeave(to, from, next) { console.log(to,"去那个页面"); console.log(from,"来自哪个页面"); next(); }
|
动态路由addRoutes
场景: 登录系统后从后台接口拿到路由数据, 动态添加到前端vue
的路由中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const routes = [ { path: '/', name: 'Home', component: 'Home__组件xxx' }, { path: '/pageA', name: 'pageA', component: 'pageA__组件xxx', } ] const router = new VueRouter({ routes })
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| const routes = [ { path: '/', name: 'Home', component: 'Home__组件xx' } ] const router = new VueRouter({ routes })
let routeFei = [ { path: '/pageA', name: 'pageA', component: 'pageA__组件xx', } ] router.addRoutes(routeFei);
|
动态路由与404
场景描述: 经过动态路由addRoutes
添加的路由,刷新浏览器后会出现找不到页面场景
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
| const routes = [ { path: '/', name: 'Home', component: 'Home__组件xx' } ] const router = new VueRouter({ routes })
let APIRouteFei = [ { path: '/pageA', name: 'pageA', component: 'pageA', }, { path: '*', name: 'NotFound', component: 'pageA__组件xx', meta: { unAuth: true } }, ] router.addRoutes(APIRouteFei); next({ ...to, replace: true })
|
知识扩展
其实在路由守卫中,只有next()是放行,其他的诸如:next(’/logo’) 、 next(to) 或者 next({ …to, replace: true })
都不是放行,而是:中断当前导航,执行新的导航
可以这么理解:
next() 是放行,但是如果next()里有参数的话,next()就像被重载一样,就有了不同的功能。
正以为如此很多情况下在使用动态添加路由addRoutes()
会遇到下面的情况:
在addRoutes()
之后第一次访问被添加的路由会白屏,这是因为刚刚addRoutes()
就立刻访问被添加的路由,然而此时addRoutes()
没有执行结束,因而找不到刚刚被添加的路由导致白屏。因此需要从新访问一次路由才行。
该如何解决这个问题 ?
此时就要使用next({ …to, replace: true })
来确保addRoutes()
时动态添加的路由已经被完全加载上去。
next({ …to, replace: true })
中的replace: true
只是一个设置信息,告诉VUE
本次操作后,不能通过浏览器后退按钮,返回前一个路由。
因此next({ …to, replace: true })
可以写成next({ …to })
跳转到404页面
1 2 3 4 5 6 7 8 9 10 11 12 13
| const routes = [ { path: '/404', name: '404', component: () => import('@/views/Error/404.vue') }, { path: '/:pathMatch(.*)', redirect: '/404', name: 'notMatch', }, ]
|
vue-router