vue历史路由实现
Vue 历史路由实现
Vue Router 支持两种路由模式:hash 模式和 history 模式。history 模式基于 HTML5 History API,允许更干净的 URL(无 #),但需要服务器配置支持。
启用 history 模式
在创建 Vue Router 实例时,通过 mode 选项设置为 'history':
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>
动态路由匹配
通过 : 定义动态路径参数,组件内通过 $route.params 访问:
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User }
]
})
编程式导航
使用 router.push、router.replace 或 router.go 实现跳转:
// 跳转到指定路径
router.push('/user/123')
// 替换当前路由
router.replace('/user/123')
// 前进或后退
router.go(-1)
路由守卫
通过全局或路由独享的守卫控制导航:
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth) {
// 检查权限
next('/login')
} else {
next()
}
})
路由懒加载
通过动态导入实现路由懒加载,优化性能:
const User = () => import('./views/User.vue')
const router = new VueRouter({
routes: [
{ path: '/user', component: User }
]
})
注意事项
history模式需要后端支持,否则刷新页面会返回 404。- 静态资源路径需使用绝对路径或正确配置
publicPath。 - 对于复杂路由,可使用嵌套路由或命名视图。
通过以上配置和方法,可以完整实现 Vue 的 history 路由模式。







