Vue Router 的 history 模式使用 createWebHistory 生成无#的干净 URL(如 /user/1001),需服务端配置兜底返回 index.html;hash 模式用 createWebHashHistory,默认启用,URL 带#(如 /#/user/1001),无需服务端配合。

Vue Router 的 history 模式和 hash 模式主要通过 history 配置项来区分,Vue 3 中不再用 mode 字段,而是使用对应的工厂函数。选哪种取决于你的部署环境和 URL 美观需求。
Hash 模式的配置方法
Hash 模式默认启用,无需后端配合,适合快速开发或静态托管场景。
- 导入
createWebHashHistory并传入history选项 - URL 会带
#,例如http://localhost:5173/#/user/1001 - 刷新页面时,# 后内容不会发给服务器,前端可直接解析恢复状态
示例代码:
import { createRouter, createWebHashHistory } from 'vue-router'<br>const router = createRouter({<br> history: createWebHashHistory(),<br> routes: [<br> { path: '/', component: Home },<br> { path: '/about', component: About }<br> ]<br>})History 模式的配置方法
History 模式生成干净 URL,但需要服务端配合,否则直接访问子路径会 404。
立即学习“前端免费学习笔记(深入)”;
- 导入
createWebHistory,通常搭配import.meta.env.BASE_URL - URL 无 #,如
http://localhost:5173/user/1001 - 必须确保所有前端路由请求都返回
index.html,由前端接管路由
示例代码:
import { createRouter, createWebHistory } from 'vue-router'<br>const router = createRouter({<br> history: createWebHistory(import.meta.env.BASE_URL),<br> routes: [<br> { path: '/', component: Home },<br> { path: '/user/:id', component: User, props: true }<br> ]<br>})服务端需注意的关键点(仅 History 模式)
如果部署在 Nginx、Apache 或 Node.js 服务上,必须配置「兜底规则」,让非静态资源请求全部返回 index.html。
- Nginx 示例:在 location 块中添加
try_files $uri $uri/ /index.html; - Apache 示例:启用
mod_rewrite,添加RewriteRule ^(.*)$ /index.html [QSA,L] - Vercel / Netlify:默认已支持,无需额外配置
怎么选?看实际需求
开发阶段或部署到 GitHub Pages、GitLab Pages 等不支持自定义重定向的平台,优先用 hash 模式;生产环境有可控服务器且追求 SEO 和 URL 体验,再上 history 模式。


















