Vue 路由入门篇:基本配置与实战应用
Vue 路由入门篇:基本配置与实战应用
Vue Router是Vue.js的官方路由管理器,可以帮助你管理页面的跳转、URL路径与视图的匹配、页面状态的保存等功能。本文将从Vue Router的概念入手,详细讲解如何安装、配置和使用Vue Router,包括创建路由、定义路由规则、使用
和 组件等。
什么是Vue Router
简单来说,Vue Router是Vue.js的官方路由管理器,可以帮助你管理页面的跳转、URL路径与视图的匹配、页面状态的保存等功能。我们对页面最简单的理解就是一个页面就是一个html文件,而网站之间页面的跳转,就是从一个html跳转到另一个html。这是早期的前端跳转逻辑。而在Vue中只需要一个html文件就够了,现在只有一个html文件了,那么我们如何实现在点击某个按钮时,跳转到另一个页面?要跳转页面的名称是什么?地址是什么?需不需要传什么参数过去?这所有的操作现在都需要由js来完成,而这部分功能封装成一个插件就是Vue Router。
如何使用Vue Router
- 安装Vue Router
npm install vue-router
- 封装路由模板
在大型项目中一般会将路由配置单独放在一个目录(如router
)是一个良好的实践。在这个目录中,通常会有一个index.js
文件作为入口配置文件,在这里定义所有的路由规则、导入需要的组件等。
- 在src下创建router目录,在router目录中创建index.js文件
import {
createRouter, // 创建路由实例
createWebHashHistory // 路由模式
} from 'vue-router'
// 页面级别组件放到views文件夹中
import Home from '../views/Home.vue'
import About from '../views/About.vue'
// 路由配置
const routes = [
{
path: '/', // 路径
component: Home, // 页面组件
meta: {
requireAuth: true,
title: '关于',
},
},
{
path: '/about',
meta: {
requireAuth: true,
},
name: 'about',
component: About,
},
]
// 路由实例
const router = createRouter({
history: createWebHashHistory(), // 路由模式
routes, // 路由配置数组
});
- 在main.js中通过import引入
import router from './router'
并初始化
app.use(router)
实战例子
在组件App.vue中使用路由
<script setup>
const name = "稀土掘金" // 数据
</script>
<template>
<div class="page">
<header class="page-header">
<img src='https://picx.zhimg.com/v2-479196399e76e67bd37bfa7aec96875d_l.jpg?source=d16d100b' class="logo-image">
<h3 class="brand">{{name}}</h3>
<nav class="menu">
<router-link class="menu-item" to="/">首页</router-link>
<router-link class="menu-item" :to="{name: 'about'}">BOT</router-link>
<router-link class="menu-item" :to="{name: 'postIndex'}">沸点</router-link>
</nav>
</header>
<main class="page-body">
<router-view />
</main>
</div>
</template>
<style lang="stylus" scoped>
.page
padding 32px
.page-header
display flex
align-items center
border-bottom 1px solid #e1e1e1
.logo-image
width 50px
height 50px
object-fit cover
border-radius 8px
margin-left 10px
padding 8px 16px
.brand
margin-right 32px
.menu-item
display inline-block
text-decoration none
color #585858
margin 8px
padding 8px 16px
.page-body
margin 24px 0
.router-link-active
color #505050
background #eeeeee
border-radius 5px
</style>
现在我们再来配置router:创建router文件夹,再在该文件夹下创建index.js
作为入口的配置文件
// 路由配置
import {
createRouter, // 创建路由实例
createWebHashHistory // 路由模式
} from 'vue-router'
// 页面级别组件放到views文件夹中
import Home from '../views/Home.vue'
import About from '../views/About.vue'
// 路由配置
const routes = [
{
path: '/', // 路径
component: Home, // 页面组件
meta: {
title: '首页',
},
},
{
path: '/about',
meta: {
title: '关于',
},
name: 'about',
component: About,
},
]
// 路由实例
const router = createRouter({
history: createWebHashHistory(), // 路由模式
routes, // 路由配置数组
});
最后我们只需要把页面组件一个一个写好就好了
Home组件
<template>
<div class='home'>
Home
梦开始的地方
</div>
<div>
<img src="https://p3-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/59901f75169541d69bf4a514a12235ec~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg54uC54Kr5LiA56KX5aSn57Gz6aWt:q75.awebp?rk3s=f64ab15b&x-expires=1741785561&x-signature=1%2FzOR5CKXcoNUYzQLBzYW8wgyzY%3D" class='img'>
</div>
</template>
<script>
</script>
<style scoped>
.home{
font-size: 50px;
color: red;
}
</style>
About组件
<template>
<div>
我是BOT
</div>
<div>
<img src="https://p3-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/b412165fff2c40cea7ae9afc2162ea1a~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg54uC54Kr5LiA56KX5aSn57Gz6aWt:q75.awebp?rk3s=f64ab15b&x-expires=1741785561&x-signature=qPwqm4l%2BckQNvMlwW4VnTK3nAXc%3D">
</div>
<div>
<button @click="goHome">点击回到上一页</button>
</div>
</template>
<script setup>
import { useRouter } from 'vue-router'
const router = useRouter() // 路由实例 总管所有的路由
const goHome = () => {
router.push('/')
}
</script>
<style scoped>
</style>
好,让我们来看看router的工作原理
- 首先
<router-link>
是 Vue Router 提供的专用组件,用于在单页面应用(SPA)中实现导航。它替代了原生的<a>
标签
<router-link>
是对<a>
标签的扩展,它具有<a>
标签的使用功能,还会将路由对应的组件显示到相应的位置上。
那使用router-link
的好处是什么呢?
- 可以无页面刷新导航:也就是在页面切换的时候不会刷新页面就能完成切换,这样就减少了页面跳转的白屏和卡顿问题,提升了用户的体验。同时也减少了服务器的压力。
- 支持动态路径
<template>
<div>
<router-link :to="`/user/${userId}`">Go to User</router-link>
</div>
</template>
<script>
export default {
data() {
return {
userId: 123,
};
},
};
</script>
而<a>
标签则只能
<a href="/user/123">Go to User</a>
router-view
是用来显示当前匹配组件的地方。
<main class="page-body">
<router-view />
</main>
我们在页面的主要内容区域显示对应的主键。 由<router-link>
和<router-view>
就实现了路由和组件的交互。
- 配置路由
import {
createRouter, // 创建路由实例
createWebHashHistory // 路由模式
} from 'vue-router'
createRouter
这是vue router 的核心方法,用于创建路由实例的,路由实例包括所以的路由规则,然后app.use(router)
将这个路由实例挂载到 Vue 应用中。
createWebHashHistory
指定路由的模式。路由有两种模式Hash 模式:createWebHashHistory
和History 模式:createWebHistory
这两种路由模式的差别就是Hash模式不影响后端,不会返回 404 错误,而History模式需要服务器重新配置,否则会出现404错误,如何你使用的是vite快速搭建vue的话,是不用配置的,vite它默认支持History 模式,无需额外配置。
- 定义路由规则
// 定义路由规则
const routes = [
{
path: '/', // 路径
component: Home, // 页面组件
meta: {
title: '首页',
},
},
{
path: '/about',
meta: {
title: '关于',
},
name: 'about',
component: About,
},
]
路由规则的基本结构:
- path属性:定义了该路由对应的 URL 路径。
- component属性:指定了当该路由被激活时应该渲染的 Vue 组件。
- meta属性:用于存储与该路由相关的额外信息或元数据,比如设置页面的标题,添加限制访问等。
- name属性:命名路由的名字,添加可读性和维护性,路由可以通过名字来导航如:
<router-link class="menu-item" to="/about">BOT</router-link>
<router-link class="menu-item" :to="{name: 'about'}">BOT</router-link>
这两条导航的效果是一样的。
- 路由实例
const router = createRouter({
history: createWebHashHistory(), // 路由模式
routes, // 路由配置数组
});
- 导出路由实例
export default router;
这样一个完整的路由配置就完成了。