vue路由实现hash
Vue 路由实现 Hash 模式
在 Vue Router 中,Hash 模式是默认的路由模式。它通过 URL 的 hash(即 # 号后的部分)来实现路由切换,不会向服务器发送请求,适合单页应用(SPA)。
启用 Hash 模式
在创建 Vue Router 实例时,默认会使用 Hash 模式。如果需要显式指定,可以设置 mode: 'hash'。
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: () => import('../views/About.vue')
}
]
const router = new VueRouter({
mode: 'hash', // 显式启用 Hash 模式
routes
})
export default router
Hash 模式的特点
- URL 中会带有
#符号,例如http://example.com/#/about。 - 改变 URL 的 hash 部分不会触发页面刷新。
- 服务器不需要任何特殊配置,因为 hash 部分不会被发送到服务器。
监听 Hash 变化
可以通过 window.onhashchange 监听 hash 变化,实现自定义逻辑。
window.onhashchange = function(event) {
console.log('Hash changed to:', window.location.hash)
}
手动修改 Hash
可以通过 window.location.hash 直接修改 hash,触发路由跳转。
window.location.hash = '/about' // 跳转到 #/about
与 History 模式的区别
- Hash 模式兼容性更好,无需服务器支持。
- History 模式 URL 更简洁(无
#),但需要服务器配置支持。 - Hash 模式适合静态部署,History 模式适合服务端渲染或静态站点生成。
注意事项
- 避免直接操作
window.location.hash,优先使用 Vue Router 的router.push或router.replace。 - Hash 模式对 SEO 不友好,如果需要 SEO 支持,建议使用 History 模式并配置服务器。
通过以上方式,可以轻松在 Vue 项目中实现 Hash 模式的路由管理。







