vue-router 的 Hash 模式 和 History 模式

vue-router 支持两种路由模式:Hash 模式History 模式。这两种模式的主要区别在于 URL 的表现形式、实现原理以及服务器配置要求。以下是它们的详细对比:


1. Hash 模式

特点
  • URL 中使用 # 符号,例如 http://example.com/#/about
  • # 后面的部分称为 hash,不会发送到服务器。
  • 通过监听 hashchange 事件实现路由切换。
优点
  1. 兼容性好
    • 支持所有浏览器,包括旧版浏览器。
  2. 无需服务器配置
    • 由于 # 后面的部分不会发送到服务器,因此无需服务器额外配置。
缺点
  1. URL 不美观
    • # 符号影响 URL 的美观性。
  2. SEO 不友好
    • 搜索引擎对 # 后面的内容处理不友好。
示例
const router = new VueRouter({
  mode: 'hash', // 默认模式
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About },
  ],
});

2. History 模式

特点
  • 使用 HTML5 History API(pushStatereplaceStategofowardback)。
  • URL 更美观,例如 http://example.com/about
  • 需要服务器配置,避免刷新时返回 404。
优点
  1. URL 美观
    • 没有 # 符号,URL 更符合传统 URL 格式。
  2. SEO 友好
    • 搜索引擎可以正确抓取页面内容。
缺点
  1. 兼容性较差
    • 不支持旧版浏览器(如 IE9 及以下)。
  2. 需要服务器配置
    • 刷新页面时,服务器需要返回 index.html,否则会返回 404。
示例
const router = new VueRouter({
  mode: 'history', // 使用 history 模式
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About },
  ],
});

3. 服务器配置

Hash 模式
  • 无需服务器配置,直接使用即可。
History 模式
  • 需要服务器配置,确保所有路由都返回 index.html
Nginx 配置
location / {
  try_files $uri $uri/ /index.html;
}
Apache 配置
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>
Node.js 配置
const express = require('express');
const path = require('path');
const app = express();

app.use(express.static(path.join(__dirname, 'dist')));

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

4. 选择模式

  • Hash 模式

    • 适合兼容性要求高的项目。
    • 适合无需服务器配置的场景。
  • History 模式

    • 适合现代浏览器项目。
    • 适合对 URL 美观性和 SEO 有要求的项目。

5. 总结

特性Hash 模式History 模式
URL 格式http://example.com/#/abouthttp://example.com/about
实现原理hashchange 事件HTML5 History API
兼容性支持所有浏览器不支持旧版浏览器(如 IE9 及以下)
服务器配置无需配置需要配置
SEO 友好性不友好友好
URL 美观性不美观美观

根据项目需求选择合适的路由模式。如果对兼容性和服务器配置有要求,可以选择 Hash 模式;如果对 URL 美观性和 SEO 有要求,可以选择 History 模式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值