前端路由【免费下载链接】vue-router The official router for Vue 2项目地址https://gitcode.com/gh_mirrors/vu/vue-router点击查看免费下载本篇技术指南以 Vue Router 2本仓库vu/vue-router官方文档《Options de construction du routeur》路由构造选项为骨架系统讲解new VueRouter(options)中全部构造选项routes、mode、base、linkActiveClass、linkExactActiveClass、scrollBehavior、parseQuery/stringifyQuery与fallback。读完本文你将能独立完成一个生产级 Vue 2 应用的路由器初始化——包括多模式选型、子应用挂载路径、导航链接高亮、滚动位置恢复与查询串定制并能对照 src/router.js 源码理解每个选项在底层是如何被消费的。一、构造选项总览一个对象驱动整个路由生命周期Vue Router 2 的路由器实例通过构造函数创建其签名与选项声明可以在 types/router.d.ts 的RouterOptions接口中看到routes、mode、fallback、base、linkActiveClass、linkExactActiveClass、parseQuery、stringifyQuery、scrollBehavior共九个可选字段。在 src/router.js 的构造函数中这些选项被依次消费constructor (options: RouterOptions {}) { this.options options this.matcher createMatcher(options.routes || [], this) // ① 路由表 → 匹配器 let mode options.mode || hash // ② 模式解析与降级 this.fallback mode history !supportsPushState options.fallback ! false if (this.fallback) mode hash if (!inBrowser) mode abstract // ③ 无浏览器 API 强制 abstract switch (mode) { // ④ 实例化对应 History case history: this.history new HTML5History(this, options.base); break case hash: this.history new HashHistory(this, options.base, this.fallback); break case abstract:this.history new AbstractHistory(this, options.base); break } }可以看到routes先行构建 matcher随后mode经过默认值 → history 降级 → 环境强制三重裁决最终落到HTML5History/HashHistory/AbstractHistory三个具体实现分别位于 src/history/html5.js、src/history/hash.js、src/history/abstract.js而base则原样透传给这些 History 实例。理解这条调用链后续每个选项的语义就一目了然。二、routes路由表与 RouteConfig 完整字段routes是唯一必填的核心选项类型为ArrayRouteConfig。官方文档给出的完整类型声明如下declare type RouteConfig { path: string; component?: Component; name?: string; // pour les routes nommées命名路由 components?: { [name: string]: Component }; // pour les vues nommées命名视图 redirect?: string | Location | Function; props?: boolean | string | Function; alias?: string | Arraystring; children?: ArrayRouteConfig; // pour les routes imbriquées嵌套路由 beforeEnter?: (to: Route, from: Route, next: Function) void; meta?: any; // 2.6.0 caseSensitive?: boolean; // 是否大小写敏感匹配默认: false pathToRegexpOptions?: Object; // 传给 path-to-regexp 编译正则的选项 }各字段作用与实战要点字段类型说明pathstring路由路径必填。顶层路由必须以/开头否则开发环境下 src/create-route-map.js 会发出 Non-nested routes must include a leading slash character 警告非严格模式下末尾/会被自动去除见下方normalizePathcomponentComponent单组件时使用源码中与components合并为{ default: route.component }的命名视图形态namestring路由命名用于router.push({ name: ... })与命名路由跳转componentsObject命名视图key 对应router-view name...redirectstring \| Location \| Function重定向目标函数形式可基于目标路由做动态重定向propsboolean \| string \| Function将路由参数作为 props 传给组件布尔/对象/函数三种形态aliasstring \| Arraystring路径别名可多个别名指向同一记录URL 不变childrenArrayRouteConfig嵌套子路由子路径会与父路径拼接beforeEnterFunction进入该路由的守卫(to, from, next)签名metaany任意元数据常用于配合导航守卫做权限、标题等标记caseSensitiveboolean2.6.0大小写敏感匹配默认falsepathToRegexpOptionsObject2.6.0透传给path-to-regexp的编译选项底层实现印证在 src/create-route-map.js 的addRouteRecord中caseSensitive会被直接映射为pathToRegexpOptions.sensitive最终与pathToRegexpOptions一起传入Regexp(path, [], pathToRegexpOptions)编译正则strict选项则控制normalizePath是否去除末尾斜杠。也就是说caseSensitive本质是pathToRegexpOptions.sensitive的便捷写法。此外alias会以路径别名的形式递归注册为独立记录matchAs指向原记录name重复时开发环境会告警这些细节都可以在源码中找到对应实现。一个覆盖多数字段的完整配置示例const routes [ { path: /user/:id, component: User, name: user, props: true, // 将 id 作为 prop 传给 User meta: { requiresAuth: true }, beforeEnter: (to, from, next) { // 进入前的守卫逻辑 next() }, children: [ { path: profile, component: UserProfile }, // /user/:id/profile { path: posts, component: UserPosts } ] }, { path: /admin, component: AdminLayout, caseSensitive: true, // 2.6.0大小写敏感 pathToRegexpOptions: { strict: true } // 2.6.0要求尾部斜杠精确匹配 }, { path: *, component: NotFound } // 通配兜底源码会将其排到匹配列表末尾 ]三、modehash / history / abstract 三种路由模式typestring默认值hash浏览器中|abstractNode.js 中可选值hash | history | abstract三种模式的官方定义hash使用 URL 的 hash#部分完成路由。在所有 Vue 支持的浏览器中都能工作包括不支持 HTML5 History API 的老浏览器。其实现见 src/history/hash.js通过getHash()读取#后的路径监听hashchange不支持pushState时或popstate事件驱动导航。history依赖 HTML5 History API且需要服务端配合配置将未知路径回退到index.html否则刷新页面会 404。完整说明见 HTML5 History 模式。实现见 src/history/html5.js导航通过pushState/replaceState改写 URL并监听popstate。abstract在所有 JavaScript 环境中工作例如 Node.js 服务端渲染。若检测不到任何浏览器 API路由器会被自动强制切换到该模式。源码级证据从 src/router.js 可见模式裁决分三步let mode options.mode || hash // 1. 未传时默认 hash this.fallback mode history !supportsPushState options.fallback ! false if (this.fallback) mode hash // 2. 不支持 pushState 时 history → hash if (!inBrowser) mode abstract // 3. 无浏览器环境强制 abstract其中supportsPushState由 src/util/push-state.js 检测。abstract模式在 src/history/abstract.js 中用内存stack数组模拟历史栈push/replace/go都不触碰window.location这正是 SSR 与测试环境如仓库 test/unit/specs/abstract-history.spec.js能够运行路由的原因。四、base应用挂载的基础路径typestring默认值/当整个单页应用部署在某个子目录下例如/app/时base必须设为/app/。此时history模式下src/history/html5.js 的getLocation(base)会先剥离base前缀再参与匹配避免base/a把/app误判为/a/pp源码注释明确引用了 issue #3555push/replace时又会把cleanPath(base route.fullPath)写回地址栏hash模式下src/history/hash.js 的checkFallback与ensureSlash同样基于base计算。const router new VueRouter({ mode: history, base: /app/, // 应用整体部署在 https://example.com/app/ 之下 routes: [ { path: /, component: Home }, { path: /about, component: About } ] })配置后访问https://example.com/app/about路由匹配到/about且router-link :to/about无需再写/app前缀详见 router-link 文档 中的说明。五、linkActiveClass 与 linkExactActiveClass全局导航高亮类名linkActiveClassstring默认router-link-active。全局配置router-link的包含匹配激活类。linkExactActiveClass2.5.0string默认router-link-exact-active。全局配置精确匹配时的激活类。两者的语义差异activeClass只要当前路由包含目标路由例如当前在/user/123/posts指向/user/123的链接也处于激活态exactActiveClass则要求完全相等。可以同时生效——一个链接可能同时挂两个类。源码证据在 src/components/link.js 的渲染逻辑中router-link的类名计算为const globalActiveClass router.options.linkActiveClass const globalExactActiveClass router.options.linkExactActiveClass const activeClassFallback globalActiveClass null ? router-link-active : globalActiveClass const exactActiveClassFallback globalExactActiveClass null ? router-link-exact-active : globalExactActiveClass classes[exactActiveClass] isSameRoute(current, compareTarget, this.exactPath) classes[activeClass] this.exact || this.exactPath ? classes[exactActiveClass] : isIncludedRoute(current, compareTarget)即精确激活由isSameRoute判定包含激活由isIncludedRoute判定若链接设置了exact或exactPath则两类合一。组件自身的active-class/exact-active-classprop 优先级高于全局选项。const router new VueRouter({ linkActiveClass: nav-item--active, // 替换默认 router-link-active linkExactActiveClass: nav-item--exact-active // 2.5.0替换默认 router-link-exact-active })六、scrollBehavior自定义滚动位置恢复typeFunction官方签名为type PositionDescriptor { x: number, y: number } | { selector: string } | ?{} type scrollBehaviorHandler ( to: Route, from: Route, savedPosition?: { x: number, y: number } ) PositionDescriptor | PromisePositionDescriptor其中to/from是导航前后的路由对象savedPosition仅在浏览器前进/后退popstate时存在包含上次离开位置{ x, y }。返回{ x, y }滚动到坐标、返回{ selector: string }滚动到元素返回空对象/false则不滚动也可返回 Promise 延迟滚动。完整理论说明见 滚动行为仓库 examples/scroll-behavior 提供了可运行的示例应用。源码证据滚动逻辑集中在 src/util/scroll.js仅当supportsPushState expectScroll时才会注册滚动监听src/history/html5.js因此该功能依赖 History APIhandleScroll在router.app.$nextTick中执行等渲染完成后再滚动返回值若带thenPromise则异步处理支持selector通过document.querySelector定位元素支持offset偏移与behavior平滑滚动见scrollToPosition。const router new VueRouter({ mode: history, scrollBehavior (to, from, savedPosition) { if (savedPosition) { return savedPosition // 前进/后退时恢复原位置 } else { return { x: 0, y: 0 } // 普通导航回到顶部 } } })进阶用法——滚动到带offset的元素并支持异步数据加载后滚动scrollBehavior (to, from, savedPosition) { if (to.hash) { return { selector: to.hash, offset: { x: 0, y: 80 } } } if (savedPosition) return savedPosition return new Promise(resolve { fetchData().then(() resolve({ x: 0, y: 0 })) }) }七、parseQuery 与 stringifyQuery自定义查询串解析2.4.0typeFunction分别用于定制查询串 → 对象与对象 → 查询串的转换完全覆盖默认实现。适用于自定义查询参数格式、特殊编码规则等场景。默认实现参考仓库 src/util/query.js 中的parseQuery按切分、拆键值重复键合并为数组stringifyQuery将对象编码为查询串undefined跳过、数组展开为多个keyvalue、null输出裸 key且encode基于encodeURIComponent并额外转义!()*、保留逗号更贴近 RFC 3986。const router new VueRouter({ parseQuery (query) { // 自定义例如把 a;b;c 解析成数组 const res {} query.split().forEach(pair { const [key, value] pair.split() res[key] res[key] ? [].concat(res[key], value) : value }) return res }, stringifyQuery (obj) { // 自定义序列化注意不要以 ? 开头类型声明中明确要求 return Object.keys(obj) .map(key ${key}${encodeURIComponent(obj[key])}) .join() } })需要注意类型声明 types/router.d.ts 中写明stringifyQuery不应输出前导?parseQuery与stringifyQuery必须成对配套否则会出现解析与序列化不对称的问题。八、fallbackhistory 不可用时的降级控制2.6.0typeboolean默认值true控制当浏览器不支持history.pushState时路由器是否自动降级为hash模式。源码见 src/router.jsthis.fallback mode history !supportsPushState options.fallback ! false if (this.fallback) { mode hash }将fallback显式设为false后在 IE9 这类不支持 History API 的浏览器中router-link的导航将退化为整页刷新因为 hash 模式被禁用。这一行为在服务端渲染SSR且需要兼容 IE9 的场景中有实际意义——hash 模式与 SSR 不兼容此时宁可让链接退化为整页刷新也要保持 history 语义。官方文档对此的说明是将fallback设为false本质上会使router-link的导航在 IE9 中触发页面重新加载。当应用由服务端渲染且需要支持 IE9 时这很有用因为 hash 模式无法与 SSR 配合。// SSR IE9 兼容场景 const router new VueRouter({ mode: history, fallback: false // 2.6.0禁止自动降级到 hash })九、完整实战一个生产级路由器初始化示例将上述选项整合一个典型的 Vue 2 生产应用初始化如下import Vue from vue import VueRouter from vue-router Vue.use(VueRouter) const router new VueRouter({ mode: history, // 需要服务端回退配置 base: /app/, // 部署子路径 linkActiveClass: nav--active, linkExactActiveClass: nav--exact-active, fallback: true, // 不支持 pushState 时自动降级 hash scrollBehavior (to, from, savedPosition) { return savedPosition || { x: 0, y: 0 } }, routes: [ { path: /, name: home, component: Home }, { path: /user/:id, name: user, component: User, props: true, meta: { requiresAuth: true }, children: [ { path: profile, component: UserProfile } ] }, { path: *, component: NotFound } ] }) new Vue({ router, render: h h(App) }).$mount(#app)小结本文以官方《Options de construction du routeur》为骨架完整覆盖了 Vue Router 2 构造器的全部九项选项routes定义路由表与RouteConfig字段语义含 2.6.0 的caseSensitive/pathToRegexpOptionsmode三种模式的选型与自动降级裁决链base的子路径部署两个链接激活类名的全局配置与精确/包含匹配差异scrollBehavior的滚动恢复与元素定位parseQuery/stringifyQuery的查询串定制以及fallback在 IE9 SSR 场景下的降级控制。每个选项都能在 src/router.js、src/history 目录、src/create-route-map.js、src/util/query.js、src/util/scroll.js 与 src/components/link.js 中找到对应的实现证据类型声明则以 types/router.d.ts 为准。配置时可对照 测试用例 与 examples 目录验证行为确保每个选项都用在正确的场景中。赞分享前端路由【免费下载链接】vue-router The official router for Vue 2项目地址https://gitcode.com/gh_mirrors/vu/vue-router点击查看免费下载相关推荐Vue Router 2 构造器选项Router Construction Options完整指南routes、mode、base 与 scrollBehavior 深度解析Vue Router 2 构造器选项Router Construction Options完整指南routes、mode、base 与 scrollBeh前端路由vue-router 构造选项完全指南从 routes 配置到 mode、scrollBehavior 与 fallback 的底层实现解析vue router 构造选项完全指南从 routes 配置到 mode、scrollBehavior 与 fallback 的底层实现解析 导读 new V前端路由Vue Router 2 命名路由Named Routes完全指南配置、跳转与源码级原理Vue Router 2 命名路由Named Routes完全指南配置、跳转与源码级原理 命名路由是 Vue Router本项目为 Vue 2 官方路由前端路由上一篇功能描述下一篇Optimum项目中的BetterTransformer兼容性问题解析创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考