vue路由实现hash
Vue 路由实现 Hash 模式
在 Vue Router 中,Hash 模式是通过 URL 的 hash(#)部分来实现路由的。这种模式兼容性较好,不需要服务器额外配置,适合大多数前端单页应用(SPA)。
基本配置
在 Vue Router 的配置中,可以通过 mode 或 history 字段来指定使用 Hash 模式。以下是 Vue Router 4.x 和 3.x 的配置方式:
Vue Router 4.x(Vue 3)
import { createRouter, createWebHashHistory } from 'vue-router';
const router = createRouter({
history: createWebHashHistory(),
routes: [...]
});
Vue Router 3.x(Vue 2)
import VueRouter from 'vue-router';
const router = new VueRouter({
mode: 'hash',
routes: [...]
});
Hash 模式的特点
- URL 格式为
http://example.com/#/path,路由变化时仅修改#后的部分。 - 页面刷新或直接访问带 hash 的 URL 时,不会向服务器发送请求,完全由前端处理路由。
- 兼容性极佳,支持所有浏览器,包括不支持 History API 的旧浏览器。
手动操作 Hash 路由
可以通过以下方式手动操作 Hash 路由:
跳转到指定路由
// Vue Router 4.x
router.push('/path');
// 原生方式
window.location.hash = '/path';
监听 Hash 变化
// Vue Router 会自动监听,无需手动处理
// 原生监听方式
window.addEventListener('hashchange', () => {
console.log('Hash changed:', window.location.hash);
});
注意事项
- Hash 模式中,
#后的路径不会被发送到服务器,因此服务器无需特殊配置。 - 如果需要隐藏
#,可以使用 History 模式,但需服务器支持。 - Hash 模式在 SEO 上略逊于 History 模式,但可以通过预渲染或 SSR 弥补。
通过以上方式,可以轻松在 Vue 项目中实现基于 Hash 的路由功能。







