重定向

使用重定向,在访问某一路由时,跳转到指定的另一路由

/router/index.ts:

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { createRouter, createWebHistory } from "vue-router"
import type { RouteRecordRaw } from "vue-router"

const routes: Array<RouteRecordRaw> = [
{
path: "/",
component: ()=> import("../components/root.vue"),
// 重定向,当访问根路由时,会跳转到/user1
// 字符串形式
// redirect: "/user1",
// 对象形式
// redirect: {
// path: "/user1"
// },
// 回调函数形式
redirect: to=> {
console.log(to)
// 返回需要跳至的路由
// 返回字符串
// return "/user"
// 返回对象,这里还可以带query参数
return {
path: "/user1",
query: {
name: "yajue",
age: 24
}
}
},
children: [
{
path: "/user1",
components: {
bbb: ()=> import("../components/B.vue"),
default: ()=> import("../components/A.vue")
}
},
{
path: "/user2",
components: {
ccc: ()=> import("../components/C.vue")
}
}
]
}
]

const router = createRouter({
// 路由的模式
history: createWebHistory(),
// 路由信息
routes
})

export default router

别名

使用别名,在路径不同时,只要符合了定义,就都能对应同一个路由组件

/router/index.ts:

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
32
33
34
35
import { createRouter, createWebHistory } from "vue-router"
import type { RouteRecordRaw } from "vue-router"

const routes: Array<RouteRecordRaw> = [
{
path: "/",
component: ()=> import("../components/root.vue"),
// 给该路由起多个别名
alias: ["/root", "/root1", "/root2"],
children: [
{
path: "/user1",
components: {
bbb: ()=> import("../components/B.vue"),
default: ()=> import("../components/A.vue")
}
},
{
path: "/user2",
components: {
ccc: ()=> import("../components/C.vue")
}
}
]
}
]

const router = createRouter({
// 路由的模式
history: createWebHistory(),
// 路由信息
routes
})

export default router