vue实现路由历史
Vue 路由历史模式实现
Vue Router 支持两种路由历史模式:hash 模式和 history 模式。默认使用 hash 模式,但 history 模式更接近原生 URL 结构,适合需要 SEO 或更简洁 URL 的项目。
Hash 模式
Hash 模式使用 URL 的 hash(#)来模拟完整 URL,无需服务器配置。其特点如下:
- URL 示例:
http://example.com/#/about - 实现简单,兼容性好
- 无需服务器支持
const router = new VueRouter({
mode: 'hash',
routes: [...]
})
History 模式
History 模式利用 HTML5 History API 实现无 # 的 URL,需要服务器支持:
- URL 示例:
http://example.com/about - 更美观的 URL
- 需要后端配合处理 404 问题
const router = new VueRouter({
mode: 'history',
routes: [...]
})
服务器配置示例
使用 history 模式时,需确保服务器在访问任意路由时返回 index.html:
Nginx 配置
location / {
try_files $uri $uri/ /index.html;
}
Apache 配置
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
Node.js Express 配置
const express = require('express')
const path = require('path')
const app = express()
app.use(express.static(path.join(__dirname, 'dist')))
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist', 'index.html'))
})
注意事项
- History 模式在生产环境需配置服务器,否则刷新页面会导致 404
- 对于静态文件托管服务(如 GitHub Pages),可能需要使用 hash 模式
- 某些 CDN 需要特别配置才能支持 history 模式
路由跳转方法
Vue Router 提供多种导航方式:
编程式导航:
// 字符串路径
router.push('/about')
// 带参数
router.push({ path: '/user', query: { id: '123' } })
// 命名路由
router.push({ name: 'user', params: { userId: '123' } })
声明式导航:
<router-link to="/about">About</router-link>
<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>
路由守卫
可用来控制导航:
全局前置守卫:
router.beforeEach((to, from, next) => {
// 验证登录状态等逻辑
next()
})
组件内守卫:

export default {
beforeRouteEnter(to, from, next) {
// 在渲染该组件的对应路由被验证前调用
next()
}
}






