vue实现hash路由
Vue 实现 Hash 路由
Vue 可以通过 vue-router 或原生方式实现 Hash 路由。以下是两种方法的详细步骤:
使用 vue-router 实现
安装 vue-router:
npm install vue-router
创建路由配置文件:
import { createRouter, createWebHashHistory } from 'vue-router'
import Home from './views/Home.vue'
import About from './views/About.vue'
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
export default router
在 main.js 中引入路由:
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
createApp(App).use(router).mount('#app')
在组件中使用路由:
<template>
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
<router-view></router-view>
</template>
原生方式实现 Hash 路由
监听 hashchange 事件:
window.addEventListener('hashchange', () => {
const hash = window.location.hash.slice(1) || '/'
console.log('Current hash:', hash)
})
动态渲染组件:
<template>
<component :is="currentComponent"></component>
</template>
<script>
export default {
data() {
return {
currentComponent: 'Home'
}
},
created() {
window.addEventListener('hashchange', this.updateComponent)
this.updateComponent()
},
methods: {
updateComponent() {
const hash = window.location.hash.slice(1) || '/'
this.currentComponent = hash === '/about' ? 'About' : 'Home'
}
},
beforeUnmount() {
window.removeEventListener('hashchange', this.updateComponent)
}
}
</script>
手动更新 Hash:

// 跳转到 About 页面
window.location.hash = '/about'
注意事项
- Hash 路由通过
#实现,不会触发页面刷新。 vue-router提供了更多功能如导航守卫、动态路由等。- 原生方式适合简单场景,复杂项目建议使用
vue-router。






