路由重定向有两种类型,一种是redirect,还有一种是alisa:
- redirect:用来将当前URL重定向到新的URL
- alisa:为路由起别名,不同路径跳转到的实际上是同一个组件
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'Login',
redirect: '/user',
},
{
path: '/user',
name: 'Reg',
component: import('../components/reg.vue'),
},
]
const router = createRouter({
history: createWebHashHistory(),
routes,
})
export default router
redire的两种写法
第一种:直接使用字符串,示例在上面
第二种:对象写法(path会自动对应到其他路由中)
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'Login',
redirect: {path:'/user'},
},
{
path: '/user',
name: 'Reg',
component: import('../components/reg.vue'),
},
]
const router = createRouter({
history: createWebHashHistory(),
routes,
})
export default router
第三种:函数写法(支持传入一个参数to,内部包含跳转之前页面的信息)
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'Login',
redirect: (to) => {
console.log(to)
return {
path: '/user',
query: {
xiaoman: '小满',
},
}
},
},
{
path: '/user',
name: 'Reg',
component: () => import('../components/reg.vue'),
},
]
const router = createRouter({
history: createWebHashHistory(),
routes,
})
export default router
alisa属性
前排提醒:若要使用alisa则属性中必须有redirect,否则ts将报类型错误
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'Login',
alias: ['/root1', '/root2'],
redirect: (to) => {
console.log(to)
return {
path: '/user',
query: {
xiaoman: '小满',
},
}
},
},
{
path: '/user',
name: 'Reg',
component: () => import('../components/reg.vue'),
},
]
const router = createRouter({
history: createWebHashHistory(),
routes,
})
export default router
此时,访问/#/root1和/#/root2跳转到的页面和直接访问/相同