1.重定向
- 字符串形式配置
当访问/uer会重定向到/user/man
const routes = [ // 这里可以随意命名 routes1 也可以
{ path: '/', redirect: "/home" },// 重定向的路径一定是下面注册过的路由的某一个 不要乱写没有创建的组件
{ path: '/news',redirect: "/home", name: '新闻', component: () => import('../views/News.vue') },
{ path: '/playing', component: Playing },
{ path: '/home', name: '玩', component: () => import('../views/Home.vue') },
{ path: '/dynamic/:id', component: () => import('../views/Dynamic.vue') },
{
path: '/user',
component: () => import('../views/User.vue'),
children: [
{ path: '/user/man', component: () => import('../views/Man.vue') },
{ path: 'woman', component: () => import('../views/Woman.vue') },
]
},
]
- 对象形式配置
const routes = [ // 这里可以随意命名 routes1 也可以
{ path: '/', redirect: { path: '/home' }, },
{ path: '/news', name: '新闻', component: () => import('../views/News.vue') },
{ path: '/playing', component: Playing },
{ path: '/home', name: '玩', component: () => import('../views/Home.vue') },
{ path: '/dynamic/:id', component: () => import('../views/Dynamic.vue') },
{
path: '/user',
component: () => import('../views/User.vue'),
children: [
{ path: '/user/man', component: () => import('../views/Man.vue') },
{ path: 'woman', component: () => import('../views/Woman.vue') },
]
},
]
2.导航守卫
- 全局前置守卫
router.beforeEach((to, from) => { // 路由守卫 也叫 路由拦截器 在做登录页面的时候使用,如果没有登陆不能通过输导航进去
if (to.path === '/news') {
return false
}
})
每个守卫方法接收三个参数:
to: Route, 即将要进入的目标 路由对象;
from: Route,当前导航正要离开的路由;
return false,不能进
return true,能进
- 全局后置守卫
使用场景一般是路由跳转结束取消loading动画
router.afterEach((to, from) => {
if (to.path === '/news') {
console.log('我去news了!')
}
})