【VueRouter】2.安装和使用
本文最后更新于 2025年7月15日 下午
Tips: VueRouter 是Vue官方为单应用专门打造的。
接下来看看如何安装VueRouter
。
分别有使用CDN
引入和使用NPM
安装两种方式。
@tab CDN
1
https://unpkg.com/vue-router@2.0.0/dist/vue-router.js
@tab NPM
1
npm install vue-router@4
这里采用CDN的方式。
其基本的使用方法是: -
使用router-link
组件来导航,通过to
来跳转指定链接(相当于<a> </a>
标签)。
-
使用router-view
组件定义路由出口,路由匹配到组件将会渲染到此处。
-
使用const routes = [{ path, component }]
来定义路由(路径和组件名)。
- 创建和挂载根实例,在 new Vue
中挂载上一步创建的路由实例 router
。
首先用命令获取库文件: 1
2wget https://labfile.oss.aliyuncs.com/courses/1262/vue.min.js
wget https://labfile.oss.aliyuncs.com/courses/10532/vue-router.js
在index.html
中写入: 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<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="vue.min.js"></script>
<script src="vue-router.js"></script>
</head>
<body>
<div id="app">
<h1>路由的使用</h1>
<p>
<!-- 使用 router-link 组件来导航 -->
<router-link to="/home">首页</router-link>
<router-link to="/hot">热门</router-link>
<router-link to="/class">分类</router-link>
</p>
<!-- 路由出口 -->
<!-- 路由匹配到的组件将渲染在这里 -->
<router-view></router-view>
</div>
<script>
const Home = { template: "<div>首页</div>" };
const Hot = { template: "<div>热门</div>" };
const Class = { template: "<div>分类</div>" };
// 定义路由
const routes = [
{ path: "/home", component: Home },
{ path: "/hot", component: Hot },
{ path: "/class", component: Class },
];
// 创建 router 实例,然后传 routes 配置
const router = new VueRouter({
routes,
});
// 创建和挂载根实例
const app = new Vue({
router,
}).$mount("#app");
</script>
</body>
</html>
页面效果: ::: demo-wrapper no-padding :::
点击不同的链接后页面只会局部刷新。