vue实现hash路由
Vue 实现 Hash 路由
在 Vue 中可以通过 vue-router 或手动监听 hashchange 事件来实现基于 Hash 的路由。
使用 vue-router 实现
安装 vue-router:

npm install vue-router
在项目中配置路由:
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
];
const router = new VueRouter({
mode: 'hash', // 使用 Hash 模式
routes,
});
new Vue({
router,
render: h => h(App),
}).$mount('#app');
在组件中使用路由:

<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
<router-view></router-view>
手动监听 hashchange 事件
如果不使用 vue-router,可以通过监听 window.onhashchange 实现简单的 Hash 路由:
export default {
data() {
return {
currentRoute: window.location.hash.slice(1) || '/',
};
},
created() {
window.addEventListener('hashchange', () => {
this.currentRoute = window.location.hash.slice(1) || '/';
});
},
methods: {
navigateTo(path) {
window.location.hash = path;
},
},
};
在模板中动态渲染组件:
<button @click="navigateTo('/')">Home</button>
<button @click="navigateTo('/about')">About</button>
<div v-if="currentRoute === '/'">Home Page</div>
<div v-else-if="currentRoute === '/about'">About Page</div>
Hash 路由的特点
- URL 格式为
http://example.com/#/path。 - 兼容性较好,支持老旧浏览器。
- 不会向服务器发送请求,仅前端处理路由变化。
- 适合静态部署或无后端支持的单页应用(SPA)。






