当前位置:首页 > VUE

vue路由实现hash

2026-02-19 11:03:31VUE

Vue 路由实现 Hash 模式

在 Vue Router 中,Hash 模式是默认的路由模式。它通过 URL 的 hash(即 # 号后的部分)来实现路由切换,不会向服务器发送请求,适合单页应用(SPA)。

vue路由实现hash

启用 Hash 模式

在创建 Vue Router 实例时,默认会使用 Hash 模式。如果需要显式指定,可以设置 mode: 'hash'

vue路由实现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.pushrouter.replace
  • Hash 模式对 SEO 不友好,如果需要 SEO 支持,建议使用 History 模式并配置服务器。

通过以上方式,可以轻松在 Vue 项目中实现 Hash 模式的路由管理。

标签: 路由vue
分享给朋友:

相关文章

vue实现点击跳转路由

vue实现点击跳转路由

Vue 实现点击跳转路由的方法 在 Vue 中实现点击跳转路由可以通过以下几种方式完成,具体取决于项目使用的路由管理工具(通常是 Vue Router)以及需求场景。 使用 router-link…

vue前端实现下载进度

vue前端实现下载进度

实现下载进度条的基本思路 在Vue中实现下载进度条,通常需要结合XMLHttpRequest或Fetch API来监听下载进度事件。通过计算已下载数据与总数据的比例,动态更新进度条的显示。 使用XM…

vue实现groupbox

vue实现groupbox

Vue 实现 GroupBox 组件 在 Vue 中实现类似 GroupBox 的效果可以通过自定义组件完成。GroupBox 通常是一个带有标题的边框容器,用于将相关控件分组显示。 基本实现方法…

vue实现分发

vue实现分发

Vue 实现分发的方法 在 Vue 中,分发(Distribution)通常指的是将内容从父组件传递到子组件,或者通过插槽(Slots)机制让父组件控制子组件的部分渲染内容。以下是几种常见的实现分发的…

vue实现webapp

vue实现webapp

Vue 实现 WebApp 的基本步骤 环境准备 确保已安装 Node.js 和 npm/yarn。通过 Vue CLI 或 Vite 创建项目: npm install -g @vue/cli v…

实现vue cli

实现vue cli

安装 Vue CLI 确保系统中已安装 Node.js(版本建议 12.x 或更高)。通过 npm 全局安装 Vue CLI: npm install -g @vue/cli 安装完成后验证版本:…