Vue-Router入门
# Vue-Router 入门
# 一、前端路由 = “单页应用中的控制器导航”
在 Java 后端中,你会定义很多 Controller,接收不同路径请求,比如 /user/list、/user/detail。
前端使用 Vue Router,也是通过路径来切换页面视图(组件),只不过是在浏览器端完成页面切换,而不是后端渲染 HTML。
Vue Router = 前端页面的“路径跳转控制器”。
# 二、安装与初始化 Router
# 1. 安装
npm install vue-router
# 2. 创建路由配置文件(推荐写在 src/router/index.js)
// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import Home from '@/views/Home.vue';
import User from '@/views/User.vue';
const routes = [
{ path: '/', component: Home },
{ path: '/user', component: User }
];
const router = createRouter({
history: createWebHistory(),
routes
});
export default router;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 3. 挂载路由到应用中(main.js)
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
createApp(App).use(router).mount('#app');
2
3
4
5
# 三、视图跳转:你从哪个“URL”加载哪个页面?
# 1. 在 App.vue 添加 <router-view />
<template>
<router-view></router-view> <!-- 相当于“子路由入口” -->
</template>
2
3
# 2. 创建页面组件
<!-- src/views/User.vue -->
<template><h2>用户页面</h2></template>
2
访问浏览器中的 /user,就会看到这个页面。
# 四、导航跳转方式(静态与编程式)
# 1. 使用 <router-link>
<router-link to="/user">进入用户页</router-link>
# 2. 使用 JS 跳转(编程式导航)
import { useRouter } from 'vue-router';
const router = useRouter();
router.push('/user'); // 类似后端的重定向
2
3
4
# 五、传参方式详解(路径、查询、状态)
# 1. 动态路径参数(类似 /user/123)
// 路由配置
{ path: '/user/:id', component: UserDetail }
// 页面跳转
router.push('/user/123')
// 在 UserDetail 组件中获取参数
import { useRoute } from 'vue-router';
const route = useRoute();
console.log(route.params.id); // 123
2
3
4
5
6
7
8
9
10
# 2. 查询参数(?key=value)
router.push({ path: '/user', query: { name: 'jack' } });
// => /user?name=jack
2
# 嵌套路由与命名路由
适用于页面中嵌套页面(如 tab 页)。
{
path: '/admin',
component: AdminLayout,
children: [
{ path: 'user', component: AdminUser },
{ path: 'role', component: AdminRole }
]
}
2
3
4
5
6
7
8
访问 /admin/user 会加载 AdminLayout + AdminUser。
# 七、导航守卫:前端权限控制核心
类比后端的拦截器、Spring Security。
# 示例:未登录用户重定向到登录页
router.beforeEach((to, from, next) => {
const token = localStorage.getItem('token');
if (to.path !== '/login' && !token) {
next('/login');
} else {
next(); // 放行
}
});
2
3
4
5
6
7
8
# 八、实战建议小练习
- 创建两个页面:用户列表
/users,用户详情/users/:id - 点击列表项跳转到详情页,展示用户 ID
- 在跳转前判断是否已登录(用导航守卫)
# 九、总结
| 概念 | 类比 Java 后端 | Vue Router |
|---|---|---|
| 页面路由控制 | Controller 路径跳转 | createRouter() |
| 参数传递 | PathVariable / RequestParam | :id, query |
| 页面跳转 | redirect、forward | router.push() |
| 权限拦截 | Spring Security / Interceptor | beforeEach() |
| 嵌套模块 | 子 Controller / 模块结构 | children 配置 |
# 补充:vue-router 工程化实践
以下是使用 vite + TypeScript 工程化项目中 vue-router 的完整用法。
# 2) vue-router
# 安装
npm install vue-router@4
# 创建 router
首先创建一个 /src/router/a5router.ts 文件,在其中定义路由
import {createRouter, createWebHashHistory} from 'vue-router'
import A51 from '../views/A51.vue'
import A52 from '../views/A52.vue'
// 路由 => 路径和组件之间的对应关系
const routes = [
{
path: '/a1',
component: A51
},
{
path: '/a2',
component: A52
}
]
const router = createRouter({
history: createWebHashHistory(), // 路径格式
routes: routes // 路由数组
})
export default router
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
createWebHashHistory 是用 # 符号作为【单页面】跳转技术,上面两个路由访问时路径格式为
- http://localhost:7070/#/a1
- http://localhost:7070/#/a2
每个路由都有两个必须属性
path:路径
component:组件
createRouter 用来创建 router 对象,作为默认导出
需要在 main.ts 中导入 router 对象:
// ...
import A5 from './views/A5.vue' // vue-router
import router from './router/a5router'
createApp(A5).use(antdv).use(router).mount('#app')
2
3
4
A5 是根组件,不必在 router 中定义,但需要在其中定义 router-view,用来控制路由跳转后,A51、A52 这些组件的显示位置,内容如下
<template>
<div class="a5">
<router-view></router-view>
</div>
</template>
2
3
4
5
效果如下


# 动态导入
import {createRouter, createWebHashHistory} from 'vue-router'
import A51 from '../views/A51.vue'
import A52 from '../views/A52.vue'
const routes = [
// ...
{
path: '/a3',
component: () => import('../views/A53.vue')
}
]
2
3
4
5
6
7
8
9
10
- 用 import 关键字导入,效果是打包时会将组件的 js 代码都打包成一个大的 js 文件,如果组件非常多,会影响页面加载速度
- 而 import 函数导入(动态导入),则是按需加载,即
- 当路由跳转到 /a3 路径时,才会去加载 A53 组件对应的 js 代码
- vue-router 官方推荐采用动态导入
# 嵌套路由
如果希望再嵌套更深层次的路由跳转,例如:希望在 A53 组件内再进行路由跳转

首先,修改 A53.vue
<template>
<div class="a53">
<router-view></router-view>
</div>
</template>
2
3
4
5
其次,再修改 /src/router/a5router.ts 文件 内容
import {createRouter, createWebHashHistory} from 'vue-router'
import A51 from '../views/A51.vue'
import A52 from '../views/A52.vue'
const routes = [
// ...
{
path: '/a3',
component: () => import('../views/A53.vue'),
children: [
{
path: 'student',
component: () => import('../views/A531.vue')
},
{
path: 'teacher',
component: () => import('../views/A532.vue')
}
]
}
]
// ...
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
将来访问 /a3/student 时,效果为

访问 /a3/teacher 时,效果为

# 重定向
用法1
import {createRouter, createWebHashHistory} from 'vue-router'
import A51 from '../views/A51.vue'
import A52 from '../views/A52.vue'
const routes = [
// ...
{
path: '/a3',
component: () => import('../views/A53.vue'),
redirect: '/a3/student', // 重定向到另外路径
children: [
{
path: 'student',
component: () => import('../views/A531.vue')
},
{
path: 'teacher',
component: () => import('../views/A532.vue')
}
]
}
]
// ...
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
效果是,页面输入 /a3,紧接着会重定向跳转到 /a3/student
用法2
import {createRouter, createWebHashHistory} from 'vue-router'
import A51 from '../views/A51.vue'
import A52 from '../views/A52.vue'
const routes = [
{
path: '/a1',
component: A51
},
{
path: '/a2',
component: A52
},
// ...
{
path: '/:pathMatcher(.*)*', // 可以匹配剩余的路径
redirect: '/a2'
}
]
// ...
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
效果是,当页面输入一个不存在路径 /aaa 时,会被 path: '/:pathMatcher(.*)*' 匹配到,然后重定向跳转到 A52 组件去
# 主页布局
借助 antdv 的 layout 组件,可以实现主页【上】【左】【右】布局
<template>
<div class="a53">
<a-layout>
<a-layout-header></a-layout-header>
<a-layout>
<a-layout-sider></a-layout-sider>
<a-layout-content>
<router-view></router-view>
</a-layout-content>
</a-layout>
</a-layout>
</div>
</template>
<style scoped>
.a53 {
height: 100%;
background-color: rgb(220, 225, 255);
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'%3E%3Ctext x='35' y='10' font-size='14' font-family='system-ui, sans-serif' text-anchor='middle' dominant-baseline='middle'%3EA53(主页)%3C/text%3E%3C/svg%3E");
padding: 20px;
box-sizing: border-box;
}
.ant-layout-header {
height: 50px;
background-color:darkseagreen;
}
.ant-layout-sider {
background-color:lightsalmon;
}
.ant-layout-content {
background-color: aliceblue;
}
.ant-layout-footer {
background-color:darkslateblue;
height: 30px;
}
.ant-layout {
height: 100%;
}
.ant-layout-has-sider {
height: calc(100% - 50px);
}
</style>
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
# 侧边栏菜单
<template>
<div class="a53">
<a-layout>
<a-layout-header></a-layout-header>
<a-layout>
<a-layout-sider>
<a-menu theme="dark" mode="inline">
<a-menu-item :key="1">
<router-link to="/a3/student">菜单1</router-link>
</a-menu-item>
<a-menu-item :key="2">
<router-link to="/a3/teacher">菜单2</router-link>
</a-menu-item>
<a-menu-item :key="3">菜单3</a-menu-item>
<a-sub-menu :key="4" title="菜单4">
<a-menu-item :key="41">菜单41</a-menu-item>
<a-menu-item :key="42">菜单42</a-menu-item>
</a-sub-menu>
</a-menu>
</a-layout-sider>
<a-layout-content>
<router-view></router-view>
</a-layout-content>
</a-layout>
</a-layout>
</div>
</template>
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
- a-menu-item 与 a-sub-menu 都必须为 key 属性唯一赋值,否则会产生混乱
- router-link 标签用来切换路由,to 是目标路由的路径
- theme 属性定义菜单的主题(默认亮色主题,dark 为暗色主题)
- mode 属性定义子菜单的展示模式(默认弹出,inline 显示在下方)
# 菜单图标
安装图标依赖
npm install @ant-design/icons-vue
菜单中使用图标
<template>
<div class="a53">
<a-layout>
<a-layout-header></a-layout-header>
<a-layout>
<a-layout-sider>
<a-menu theme="dark" mode="inline">
<a-menu-item :key="1">
<template #icon>
<highlight-outlined />
</template>
<router-link to="/a3/student">菜单1</router-link>
</a-menu-item>
<a-menu-item :key="2">
<template #icon>
<align-center-outlined />
</template>
<router-link to="/a3/teacher">菜单2</router-link>
</a-menu-item>
<a-menu-item :key="3">
<template #icon>
<strikethrough-outlined />
</template>
菜单3</a-menu-item>
<a-sub-menu :key="4" title="菜单4">
<template #icon>
<sort-descending-outlined />
</template>
<a-menu-item :key="41">菜单41</a-menu-item>
<a-menu-item :key="42">菜单42</a-menu-item>
</a-sub-menu>
</a-menu>
</a-layout-sider>
<a-layout-content>
<router-view></router-view>
</a-layout-content>
</a-layout>
</a-layout>
</div>
</template>
<script setup lang="ts">
import {HighlightOutlined, AlignCenterOutlined, StrikethroughOutlined, SortDescendingOutlined} from '@ant-design/icons-vue'
</script>
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
- 图标组件没有全局绑定,需要 import 之后才能使用
- 用
<template #icon></template>插槽,才能确定图标展示的位置(菜单文字之前)
# 二次封装图标组件
最终希望用统一的图标组件去使用图标,图标名只是作为一个属性值传递进去,例如:
使用者
<template>
<a-icon icon="highlight-outlined"></a-icon>
<a-icon icon="align-center-outlined"></a-icon>
<a-icon icon="strikethrough-outlined"></a-icon>
<a-icon icon="sort-descending-outlined"></a-icon>
</template>
<script setup lang="ts">
import AIcon from '../components/AIcon1.vue'
</script>
2
3
4
5
6
7
8
9
# 方法1,使用 vue 组件
<script lang="ts" setup>
import {HighlightOutlined, AlignCenterOutlined, StrikethroughOutlined, SortDescendingOutlined} from '@ant-design/icons-vue'
const props = defineProps<{icon:string}>()
</script>
<template>
<highlight-outlined v-if="icon==='highlight-outlined'"></highlight-outlined>
<align-center-outlined v-else-if="icon==='align-center-outlined'"></align-center-outlined>
<strikethrough-outlined v-else-if="icon==='strikethrough-outlined'"></strikethrough-outlined>
<sort-descending-outlined v-else-if="icon==='sort-descending-outlined'"></sort-descending-outlined>
</template>
2
3
4
5
6
7
8
9
10
- 缺点:实现太笨
# 方法2,使用函数式组件
import { h } from "vue"
import * as Icons from '@ant-design/icons-vue'
interface Module {
[p:string]: any
}
// 参数1: 组件属性
const AIcon = (props:{icon:string}) => {
// console.log(props.icon)
// console.log(Icons)
// 参数1: 组件对象
const im: Module = Icons
return h(im[toCamelCase(props.icon)])
}
export default AIcon
// 将-分隔的单词转换为大驼峰命名的单词
function toCamelCase(str: string) { // highlight-outlined
return str.split('-') // ['highlight', 'outlined']
.map((e)=> e.charAt(0).toUpperCase() + e.slice(1) ) // ['Highlight', 'Outlined']
.join('')
}
/*
Icons 的结构如下
{
HighlightOutlined: HighlightOutlined组件对象,
MonitorOutlined: MonitorOutlined组件对象,
...
}
*/
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
- 需要动态生成标签的时候,可以考虑使用函数式组件
# 方法3,使用 jsx 组件
首先,安装
npm install @vitejs/plugin-vue-jsx -D
配置 vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue(), vueJsx()]
})
2
3
4
5
6
7
8
编写一个 Hi.tsx 组件
export default {
props: {
msg: String
},
setup(props: { msg: string }) {
return () => <h5>{props.msg}</h5>
}
}
2
3
4
5
6
7
8
然后被其它组件使用
<script setup lang="ts">
import Hi from '../components/Hi'
</script>
<template>
<Hi msg="Hello,World"></Hi>
</template>
2
3
4
5
6
7
用 jsx 实现图标组件
import * as Icons from '@ant-design/icons-vue'
interface Module {
[p:string]: any
}
function toCamelCase(str: string) { // highlight-outlined
return str
.split("-") // ['highlight', 'outlined']
.map((e) => e.charAt(0).toUpperCase() + e.slice(1)) // ['Highlight', 'Outlined']
.join(""); // HighlightOutlined
}
export default {
props: {
icon: String
},
setup(props: {icon: string}) {
const im: Module = Icons
const tag = im[toCamelCase(props.icon)] // 图标组件
// HighlightOutlined
return ()=> <tag></tag> // 返回组件标签
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 动态路由与菜单
# 路由文件
a6router.js
import { createRouter, createWebHashHistory } from 'vue-router'
import { useStorage } from '@vueuse/core'
import { Route, Menu } from '../model/Model8080'
const clientRoutes = [
{
path: '/login',
name: 沉梦听雨
component: () => import('../views/A6Login.vue')
},
{
path: '/404',
name: 沉梦听雨
component: () => import('../views/A6NotFound.vue')
},
{
path: '/',
name: 沉梦听雨
component: () => import('../views/A6Main.vue')
},
{
path: '/:pathMatcher(.*)*',
name: 沉梦听雨
redirect: '/404'
}
]
const router = createRouter({
history: createWebHashHistory(),
routes: clientRoutes
})
export const serverMenus = useStorage<Menu[]>('serverMenus', [])
const serverRoutes = useStorage<Route[]>('serverRoutes', [])
addServerRoutes(serverRoutes.value)
export function addServerRoutes(routeList: Route[]) {
for (const r of routeList) {
if (r.parentName) {
router.addRoute(r.parentName, {
path: r.path,
component: () => import(r.component),
name: 沉梦听雨
})
}
}
serverRoutes.value = routeList
}
export function resetRoutes() {
for (const r of clientRoutes) {
router.addRoute(r)
}
serverRoutes.value = null
serverMenus.value = null
}
export default router
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
56
57
本文件重要的函数及变量
- addServerRoutes 函数向路由表中添加由服务器提供的路由,路由分成两部分
- clientRoutes 这是客户端固定的路由
- serverRoutes 这是服务器变化的路由,存储于 localStorage
- resetRoutes 函数用来将路由重置为 clientRoutes
- vue-router@4 中的 addRoute 方法会【覆盖】同名路由,这是这种实现的关键
- 因此,服务器返回的路由最好是 main 的子路由,这样重置时就会比较简单,用之前的 main 一覆盖就完事了
- serverMenus 变量记录服务器变化的菜单,存储于 localStorage
# 登录组件
动态路由应当在登录时生成,A6Login.vue
<template>
<div class="login">
<a-form :label-col="{ span: 6 }" autocomplete="off">
<a-form-item label="用户名" v-bind="validateInfos.username">
<a-input v-model:value="dto.username" />
</a-form-item>
<a-form-item label="密码" v-bind="validateInfos.password">
<a-input-password v-model:value="dto.password" />
</a-form-item>
<a-form-item :wrapper-col="{ offset: 6, span: 16 }">
<a-button type="primary" @click="onClick">Submit</a-button>
</a-form-item>
</a-form>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Form } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import axios from '../api/request'
import { useRequest } from 'vue-request'
import { AxiosRespToken, LoginDto, AxiosRespMenuAndRoute } from '../model/Model8080'
import { resetRoutes, addServerRoutes, serverMenus } from '../router/a6router'
const dto = ref({username:'', password:''})
const rules = ref({
username: [
{required: true, message:'用户名必填'}
],
password:[
{required: true, message:'密码必填'}
]
})
const { validateInfos, validate } = Form.useForm(dto, rules)
const router = useRouter()
const { runAsync:login } = useRequest<AxiosRespToken, LoginDto[]>((dto)=> axios.post('/api/loginJwt', dto), {manual:true})
const { runAsync:menu } = useRequest<AxiosRespMenuAndRoute, string[]>((username)=> axios.get(`/api/menu/${username}`), {manual:true})
async function onClick() {
try {
await validate()
const loginResp = await login(dto.value
if(loginResp.data.code === 200) { // 登录成功
const token = loginResp.data.data.token
const menuResp = await menu(dto.value.username)
const routeList = menuResp.data.data.routeList
addServerRoutes(routeList)
serverMenus.value = menuResp.data.data.menuTree
router.push('/')
})
} catch (e) {
console.error(e)
}
}
onMounted(()=>{
resetRoutes()
})
</script>
<style scoped>
.login{
margin: 200px auto;
width: 25%;
padding: 20px;
height: 180px;
background-color: antiquewhite;
}
</style>
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
56
57
58
59
60
61
62
63
64
65
- 登录成功后去请求
/api/menu/{username}获取该用户的菜单和路由 - router.push 方法用来以编程方式跳转至主页路由
# 主页组件
A6Main.vue
<template>
<div class="a6main">
<a-layout>
<a-layout-header>
</a-layout-header>
<a-layout>
<a-layout-sider>
<a-menu mode="inline" theme="dark">
<template v-for="m1 of serverMenus">
<a-sub-menu v-if="m1.children" :key="m1.id" :title="m1.title">
<template #icon><a-icon :icon="m1.icon"></a-icon></template>
<a-menu-item v-for="m2 of m1.children" :key="m2.id">
<template #icon><a-icon :icon="m2.icon"></a-icon></template>
<router-link v-if="m2.routePath" :to="m2.routePath">{{m2.title}}</router-link>
<span v-else>{{m2.title}}</span>
</a-menu-item>
</a-sub-menu>
<a-menu-item v-else :key="m1.id">
<template #icon><a-icon :icon="m1.icon"></a-icon></template>
<router-link v-if="m1.routePath" :to="m1.routePath">{{m1.title}}</router-link>
<span v-else>{{m1.title}}</span>
</a-menu-item>
</template>
</a-menu>
</a-layout-sider>
<a-layout-content>
<router-view></router-view>
</a-layout-content>
</a-layout>
</a-layout>
</div>
</template>
<script setup lang="ts">
import AIcon from '../components/AIcon3' // jsx icon 组件
import { serverMenus } from '../router/a6router'
</script>
<style scoped>
.a6main {
height: 100%;
background-color: rgb(220, 225, 255);
box-sizing: border-box;
}
.ant-layout-header {
height: 50px;
background-color:darkseagreen;
}
.ant-layout-sider {
background-color:lightsalmon;
}
.ant-layout-content {
background-color: aliceblue;
}
.ant-layout-footer {
background-color:darkslateblue;
height: 30px;
}
.ant-layout {
height: 100%;
}
.ant-layout-has-sider {
height: calc(100% - 50px);
}
</style>
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# token 使用
- 获取用户信息,例如服务器端可以把用户名、该用户的路由、菜单信息都统一从 token 返回
- 前端路由跳转依据,例如跳转前检查 token,如果不存在,表示未登录,就避免跳转至某些路由
- 后端 api 访问依据,例如每次发请求携带 token,后端需要身份校验的 api 需要用到