安装和使用

Sy_ Lv6

Tips: VueRouter 是Vue官方为单应用专门打造的。

接下来看看如何安装VueRouter

分别有使用CDN引入和使用NPM安装两种方式。

:::: code-tabs
@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
2
wget https://labfile.oss.aliyuncs.com/courses/1262/vue.min.js
wget https://labfile.oss.aliyuncs.com/courses/10532/vue-router.js

index.html中写入:

:collapsed-lines
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
20250226184948
:::

点击不同的链接后页面只会局部刷新。

  • 标题: 安装和使用
  • 作者: Sy_
  • 创建于 : 2025-06-15 00:51:35
  • 更新于 : 2025-06-15 00:51:35
  • 链接: https://shenying.online//demo/i99ir9kd/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论
目录
安装和使用