vue 路由

Vue.js 路由小结

概述

Vue.js 是一个流行的前端JavaScript框架,其中的路由功能允许我们构建单页面应用(SPA),而无需服务器端渲染。Vue Router 是官方推荐的路由管理库,它为我们提供了声明式的路由配置和导航解决方案。

基本使用

安装

首先,我们需要安装 Vue Router。在使用 Vue CLI 创建项目时,可以选择包含 Vue Router。如果已经有了 Vue 项目,可以通过 npm 安装:

npm install vue-router

创建路由

创建路由很简单,只需使用 VueRouter 对象的 routes 属性即可。例如:

import Vue from 'vue';

import VueRouter from 'vue-router';

Vue.use(VueRouter);

const routes = [

{ path: '/home', component: Home },

{ path: '/about', component: About },

];

const router = new VueRouter({

routes, // (缩写) 等同于 routes: routes

});

使用路由

在 Vue 实例中,我们可以使用 <router-view> 组件来渲染匹配到的路由组件。然后,在我们的 HTML 模板中,我们可以使用 Vue Router 提供的导航组件,如 <router-link> 来创建链接。

<div id="app">

<router-view></router-view>

</div>

<nav>

<router-link to="/home">Home</router-link> |

<router-link to="/about">About</router-link>

</nav>

进阶配置

嵌套路由

Vue Router 支持嵌套路由,这在构建复杂的应用时很有用。我们可以在一个路由中定义另一个路由,这样就可以在一个页面上展示多个子视图。

const routes = [

{

path: '/parent',

component: ParentView,

children: [

{ path: 'child', component: ChildView },

{ path: 'other-child', component: OtherChildView },

],

},

];

命名路由

为了使路由更易于管理,我们可以为它们提供名称。这样,我们就可以在链接和重定向中使用这些名称,而不是硬编码路径。

const routes = [

{ name: 'home', path: '/home', component: Home },

{ name: 'about', path: '/about', component: About },

];

路由参数

我们还可以在路由中使用参数。参数使用冒号 ( : ) 标记,当匹配到一个路由时,参数值会被设置到 this.$route.params ,可以在每个组件内使用。

const routes = [

{ path: '/user/:username', component: User },

];

// 在组件中访问参数

this.$route.params.username;

通配符路由

通配符路由允许我们匹配所有路径或以特定前缀开始的路径。当使用一个通配符时, $route.params 内会自动添加一个名为 pathMatch 参数,它包含了 URL 通过通配符被匹配的部分。

const routes = [

{ path: '*', component: NotFoundView }, // 匹配所有路径

{ path: '/user-*', component: User }, // 匹配以 '/user-' 开头的任意路径

];

导航守卫

Vue Router 还提供了导航守卫,可以在路由切换之前或之后执行一些操作。我们可以使用 beforeRouteEnter , beforeRouteUpdate , beforeRouteLeave 等钩子函数来实现各种逻辑。

历史模式

Vue Router 支持两种历史模式: hash 和 history 。默认情况下,Vue Router 使用 hash 模式,URL 以 # 开头。如果我们希望使用 history API 来实现无 hash 的 URL,可以在创建 router 实例时指定 mode: 'history' 。

总结

Vue Router 为 Vue.js 提供了强大的路由管理功能,使得构建单页面应用变得简单而高效。通过灵活地配置路由、使用命名路由和路由参数、以及利用导航守卫和历史模式,我们可以轻松地管理应用的状态和导航。

相关推荐
懒得不想起名字7 分钟前
flutter 使用go_router 和 page_transition定义页面动画
前端
多加点辣也没关系15 分钟前
JavaScript|第6章:流程控制语句
开发语言·前端·javascript
csj5016 分钟前
前端基础之《React(11)—state声明式》
前端·react.js
程序员晓琪16 分钟前
深入解析:从 Webpack 到 Vite,多入口多端项目的工程化迁移实战
前端·webpack·vite
涛涛ing18 分钟前
Vue 3.6 还没正式发布,但前端的方向已经被它定下来了
前端
用户9385156350719 分钟前
手写迷你 Cursor 终端:深入 Node.js child_process 的 spawn 核心实现
javascript·后端
阿新聊ai20 分钟前
Claude Code 为什么总不懂你的项目?缺一张「项目地图」
前端·后端·面试
暗冰ཏོ29 分钟前
Spring Boot + Vue3 订单支付模块技术实现:支付单、回调验签、幂等处理与余额扣减
前端·spring boot·后端·vue·微信支付·支付宝支付
Csvn32 分钟前
AbortController 不止能取消 Fetch!3 个你不知道的隐藏用法
前端·javascript
大流星34 分钟前
LangChainJS之Runnable(三)
javascript·langchain