vue路由模式实现
Vue 路由模式实现
Vue Router 是 Vue.js 的官方路由管理器,支持多种路由模式。常见的路由模式包括 Hash 模式 和 History 模式,分别适用于不同的场景。
Hash 模式
Hash 模式使用 URL 的哈希部分(#)来实现路由,兼容性较好,无需服务器额外配置。
import { createRouter, createWebHashHistory } from 'vue-router'
const router = createRouter({
history: createWebHashHistory(),
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
})
- 特点:URL 形如
http://example.com/#/about,哈希后的内容不会发送到服务器。 - 适用场景:无需服务器配置的静态部署或旧版浏览器兼容。
History 模式
History 模式基于 HTML5 History API,URL 更简洁(无 #),但需要服务器支持。
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
})
- 特点:URL 形如
http://example.com/about,需服务器配置避免 404 错误。 - 服务器配置示例(以 Nginx 为例):
location / { try_files $uri $uri/ /index.html; } - 适用场景:需要美观 URL 且能控制服务器配置的场景。
路由模式的选择建议
- Hash 模式:简单快捷,适合静态站点或无需 SEO 的 SPA。
- History 模式:更专业的 URL 格式,适合需要 SEO 或服务端渲染的场景。
动态路由与参数传递
路由支持动态路径参数,通过 :param 定义:
routes: [
{ path: '/user/:id', component: User }
]
组件中通过 useRoute() 获取参数:
import { useRoute } from 'vue-router'
const route = useRoute()
console.log(route.params.id) // 获取动态参数
导航守卫
路由守卫用于控制导航行为,例如权限验证:
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login')
} else {
next()
}
})
通过合理选择路由模式并结合动态路由、导航守卫等功能,可以构建灵活且强大的前端路由系统。







