vue-router
支持两种路由模式:Hash 模式 和 History 模式。这两种模式的主要区别在于 URL 的表现形式、实现原理以及服务器配置要求。以下是它们的详细对比:
1. Hash 模式
特点
- URL 中使用
#
符号,例如http://example.com/#/about
。 #
后面的部分称为 hash,不会发送到服务器。- 通过监听
hashchange
事件实现路由切换。
优点
- 兼容性好:
- 支持所有浏览器,包括旧版浏览器。
- 无需服务器配置:
- 由于
#
后面的部分不会发送到服务器,因此无需服务器额外配置。
- 由于
缺点
- URL 不美观:
#
符号影响 URL 的美观性。
- SEO 不友好:
- 搜索引擎对
#
后面的内容处理不友好。
- 搜索引擎对
示例
const router = new VueRouter({
mode: 'hash', // 默认模式
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About },
],
});
2. History 模式
特点
- 使用 HTML5 History API(
pushState
、replaceState
、go
、foward
、back
)。 - URL 更美观,例如
http://example.com/about
。 - 需要服务器配置,避免刷新时返回 404。
优点
- URL 美观:
- 没有
#
符号,URL 更符合传统 URL 格式。
- 没有
- SEO 友好:
- 搜索引擎可以正确抓取页面内容。
缺点
- 兼容性较差:
- 不支持旧版浏览器(如 IE9 及以下)。
- 需要服务器配置:
- 刷新页面时,服务器需要返回
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/#/about | http://example.com/about |
实现原理 | hashchange 事件 | HTML5 History API |
兼容性 | 支持所有浏览器 | 不支持旧版浏览器(如 IE9 及以下) |
服务器配置 | 无需配置 | 需要配置 |
SEO 友好性 | 不友好 | 友好 |
URL 美观性 | 不美观 | 美观 |
根据项目需求选择合适的路由模式。如果对兼容性和服务器配置有要求,可以选择 Hash 模式;如果对 URL 美观性和 SEO 有要求,可以选择 History 模式。