vue的history和hash模式有什么不一样

Vue Router 的 History 模式 ​ 和 Hash 模式​ 是两种不同的路由实现方式,主要区别如下:

1. URL 表现形式不同

复制代码
// Hash 模式
http://example.com/#/user/profile
// URL 中带有 # 符号

// History 模式
http://example.com/user/profile
// URL 看起来更自然,没有 # 符号

2. 实现原理不同

Hash 模式

  • 基于 window.location.hashonhashchange事件

  • 只改变 URL 中 # 后面的部分,不会触发页面刷新

  • 不会将 URL 发送到服务器

    // 改变 hash
    window.location.hash = '/user'

    // 监听变化
    window.addEventListener('hashchange', () => {
    console.log('hash changed:', window.location.hash)
    })

History 模式

  • 基于 HTML5 History API(pushState、replaceState)

  • 可以修改完整的 URL 而不刷新页面

  • 需要服务器端配合

    // 添加历史记录
    history.pushState({}, '', '/user')

    // 替换当前历史记录
    history.replaceState({}, '', '/user')

3. 服务器配置要求

Hash 模式

  • 不需要服务器特殊配置

  • 因为 # 后面的内容不会被发送到服务器

  • 部署简单,所有路由都指向同一个 HTML 文件

History 模式

  • 需要服务器配置

  • 用户直接访问或刷新子路由时,服务器会返回 404

  • 需要配置所有路径都返回 index.html

    Nginx 配置示例

    location / {
    try_files uri uri/ /index.html;
    }

4. 兼容性

  • Hash 模式:兼容性更好,支持 IE8+

  • History 模式:需要 IE10+ 或现代浏览器支持

5. SEO 友好性

  • Hash 模式:不利于 SEO,# 后面的内容传统爬虫不会抓取

  • History 模式:对 SEO 更友好,URL 完整可被爬虫识别

6. 配置方式

复制代码
// router/index.js
import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'

// Hash 模式
const router = createRouter({
  history: createWebHashHistory(),
  routes: [...]
})

// History 模式
const router = createRouter({
  history: createWebHistory(),
  routes: [...]
})

使用建议

  1. 使用 Hash 模式

    • 简单项目或 demo

    • 没有服务器配置权限

    • 需要兼容低版本浏览器

    • 不关心 SEO

  2. 使用 History 模式

    • 需要干净的 URL

    • 需要 SEO 支持

    • 有服务器配置权限

    • 现代浏览器项目

注意事项

  • 使用 History 模式时,确保服务器已正确配置

  • 两种模式在开发环境下通常都能正常工作,差异主要在部署时

  • Vue Router 会自动根据模式使用相应的底层 API

相关推荐
子兮曰5 小时前
OpenClaw入门:从零开始搭建你的私有化AI助手
前端·架构·github
吴仰晖5 小时前
使用github copliot chat的源码学习之Chromium Compositor
前端
1024小神5 小时前
github发布pages的几种状态记录
前端
不像程序员的程序媛7 小时前
Nginx日志切分
服务器·前端·nginx
北原_春希7 小时前
如何在Vue3项目中引入并使用Echarts图表
前端·javascript·echarts
JY-HPS7 小时前
echarts天气折线图
javascript·vue.js·echarts
尽意啊7 小时前
echarts树图动态添加子节点
前端·javascript·echarts
吃面必吃蒜7 小时前
echarts 极坐标柱状图 如何定义柱子颜色
前端·javascript·echarts
O_oStayPositive7 小时前
Vue3使用ECharts
前端·javascript·echarts
竹秋…7 小时前
echarts自定义tooltip中的内容
前端·javascript·echarts