Vue Router 支持 两种 路由模式:
- Hash 模式(默认模式)
- History 模式
这两种模式的主要区别在于 URL 的表现形式和对服务器的要求。以下是它们的详细说明和区别:
1. Hash 模式
Hash 模式是 Vue Router 的默认模式,URL 中会带有一个 #
符号。
特点:
- URL 格式:
http://example.com/#/home
- 原理:通过
window.location.hash
实现路由切换。 - 兼容性:兼容所有浏览器,包括不支持 HTML5 History API 的旧浏览器。
- 服务器支持:不需要服务器额外配置,适合静态部署。
示例:
const router = new VueRouter({
mode: 'hash', // 默认模式,可以不写
routes: [
{ path: '/home', component: Home },
{ path: '/about', component: About }
]
});
2. History 模式
History 模式使用 HTML5 History API(pushState
和 replaceState
)来实现路由切换,URL 中没有 #
符号。
特点:
- URL 格式:
http://example.com/home
- 原理:通过
history.pushState
和history.replaceState
实现路由切换。 - 兼容性:需要现代浏览器支持(IE10+)。
- 服务器支持:需要服务器额外配置,确保所有路由都返回同一个 HTML 文件(通常是
index.html
),否则刷新页面会导致 404 错误。
示例:
const router = new VueRouter({
mode: 'history', // 使用 History 模式
routes: [
{ path: '/home', component: Home },
{ path: '/about', component: About }
]
});
两种模式的区别
特性 | Hash 模式 | History 模式 |
---|---|---|
URL 格式 | 带 # ,如 http://example.com/#/home | 不带 # ,如 http://example.com/home |
实现原理 | 基于 window.location.hash | 基于 HTML5 History API |
兼容性 | 兼容所有浏览器 | 需要现代浏览器支持(IE10+) |
服务器配置 | 无需额外配置 | 需要配置服务器支持 |
SEO 友好性 | 不友好(搜索引擎可能忽略 # 后的内容) | 更友好 |
刷新页面 | 不会导致 404 错误 | 可能导致 404 错误(需服务器配置) |
服务器配置(History 模式)
如果使用 History 模式,需要对服务器进行配置,确保所有路由都返回 index.html
文件。以下是常见服务器的配置示例:
1. Nginx
location / {
try_files $uri $uri/ /index.html;
}
2. 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>
3. Node.js(Express)
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');
});
如何选择路由模式?
- Hash 模式:
- 适合简单的项目或需要兼容旧浏览器的场景。
- 不需要服务器额外配置。
- History 模式:
- 适合需要更美观 URL 的项目。
- 需要服务器支持,适合现代浏览器。
总结
Vue Router 支持 Hash 模式 和 History 模式:
- Hash 模式:URL 带
#
,兼容性好,无需服务器配置。 - History 模式:URL 不带
#
,更美观,但需要服务器支持。
根据项目需求和部署环境选择合适的路由模式。
THE END
暂无评论内容