Vue Router 重定向和命名
重定向和命名
重定向
通过routes配置来完成。
参数
1.字符串
{
path: '/',
name: 'Home',
component: () => import('@/views/Home'),
redirect:'/about'
}
2.对象
{
path: '/',
name: 'Home',
component: () => import('@/views/Home'),
redirect: {name: 'About'}
}
重定向到指定的命名路由。
3.方法(动态返回重定向目标)
{
path: '/users/:userId',
name: 'User',
redirect: to => {
return {
path: '/newUsers',
query: {
id: to.params.userId
}
}
},
component: NewUser
}
方法接收目标路由作为参数(to),在上文目标路由就是'/users/:userId'。
箭头函数返回一个由新路径加上路由参数组成的对象。
在写redirect时,可以省略component配置,因为它从没有被直接访问过(每次都会被重定向到别的组件),所以没有组件要渲染。
唯一的例外是嵌套路由,若一个路由记录有children和redirect属性,它也应该有component属性:
{
path: '/about',
name: 'About',
component: () => import('@/views/About'),
redirect: '/about/leftSidebar',
children: [
{
path: 'leftSidebar',
component: () => import('@/views/LeftSidebar')
}
]
}
其中该redirect的路径应该和嵌套路由路径应该有关联,若没有写component,则渲染不出来组件。
相对重定向
{
path: '/about',
redirect: to => {
return to.path + '/leftSidebar'
}
}
别名
{
path: '/',
name: 'Home',
component: () => import('@/views/Home'),
alias: '/home'
}
路径'/'的别名是'/home',意味着当访问'/home'时,URL仍然是/home,但会被路由匹配成'/',当然,访问'/'时,仍旧被匹配为'/'。
通过别名,可以自由地将UI结构映射到一个任意URL,而不受配置的嵌套结构的限制。
别名以/开头,则嵌套路径中的路径称为绝对路径。
Vue Router映射的url路径默认前面会加一个#(受哈希模式影响)。
{
path: '/about',
name: 'About',
component: () => import('@/views/About'),
children: [
{
path: '',
component: () => import('@/views/LeftSidebar'),
alias: ['/leftSidebar']
}
]
}
通过路径'/#/leftSidebar'就可以渲染组件LeftSidebar,而不必通过/about。
不过'/about'同样能访问到组件LeftSidebar。
若路由中有参数,确保在任何绝对别名中包含它们。
{
path: '/about/:id',
name: 'About',
component: () => import('@/views/About'),
children: [
{
path: '',
component: () => import('@/views/LeftSidebar'),
alias: ['/:id','/leftSidebar']
}
]
}
路径'/about/:id'、'/:id'、'/leftSidebar'都能访问到LeftSidebar组件(如果是自己在浏览器地址框上输入,记得前面加#)。