官方:vue-router 默认 hash 模式 —— 使用 URL 的 hash 来模拟一个完整的 URL,于是当 URL 改变时,页面不会重新加载。如果不想要很丑的 hash,我们可以用路由的 history 模式,这种模式充分利用 history.pushState API 来完成 URL 跳转而无须重新加载页面。
其实很多人觉得这两个模式只是地址栏不同而已,或者说只是美观不美观的问题,个人觉得其实并非完全如此。大家如果做过项目上线应该知道,使用history模式是需要后端配合的,后端具体做了啥?如下:
1 2 3 4 5 6 7 8 | <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L] </IfModule> |
1 2 3 | location / { try_files $uri $uri/ /index.html; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | const http = require('http') const fs = require('fs') const httpPort = 80 http.createServer((req, res) => { fs.readFile('index.htm', 'utf-8', (err, content) => { if (err) { console.log('We cannot open "index.htm" file.') } res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }) res.end(content) }) }).listen(httpPort, () => { console.log('Server listening on: http://localhost:%s', httpPort) }) |
不管是什么后端语言,它其实要做的事情只有一个,就是在你前端访问二级页面时候服务器找不到对应资源,原本应该返回404,那么现在强制给你返回index.html首页,配合前端的路由规则,然后前端显示对应的组件
那这么看来,是不是就是可以理解,如果是用history模式,那么你在请求二级页面刷新时候,其实你执行过程中比模式的hash多弯一步路,这可能就是最根本的差别了。
上一篇:推荐Visual Studio Code快速编写vue.js的神器插件
支付宝扫一扫打赏
微信扫一扫打赏
共 0 条评论关于"Vue Router中hash和history模式区别"
最新评论