命名路由

除了path外,还可以给每个路由提供不重复的name,name有以下优点:

  • 没有硬编码的URL
  • params的自动编码/解码
  • 防止在URL中出现打字错误
  • 绕过路径排序

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

const routes:Array<RouteRecordRaw> = [
{
path: "/",
// 名称
name: "Login",
component: ()=> import("../components/login.vue")
},
{
path: "/reg",
name: "Reg",
component: ()=> import("../components/reg.vue")
}
]

const router = createRouter({
history: createWebHistory(),
routes
})

export default router

App.vue:

1
2
3
4
5
6
7
8
9
10
11
12
<template>
<div>
<h1>Vue-Router test</h1>
<div>
<!-- 传含有name属性的对象 -->
<router-link :to="{name:'Login'}">login</router-link>
<router-link :to="{name:'Reg'}" style="margin-left: 10px;">reg</router-link>
</div>
<hr>
<router-view></router-view>
</div>
</template>

编程式导航

如果需要在路由跳转时候完成一些额外的逻辑,可以使用编程式导航:

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
<template>
<div>
<h1>Vue-Router test</h1>
<div>
<button @click="toPage('/')">login</button>
<button @click="toPage('/reg')">reg</button>
</div>
<hr>
<router-view></router-view>
</div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'

const router = useRouter()

const toPage = (str:string)=> {
// 字符串跳转方式
// router.push(str)

// 对象跳转方式
router.push({
path: str
// 也可以使用name
// name: str
})
}
</script>