唯品秀前端博客

官方:vue-router 默认 hash 模式 —— 使用 URL 的 hash 来模拟一个完整的 URL,于是当 URL 改变时,页面不会重新加载。如果不想要很丑的 hash,我们可以用路由的 history 模式,这种模式充分利用 history.pushState API 来完成 URL 跳转而无须重新加载页面。

具体区别

其实很多人觉得这两个模式只是地址栏不同而已,或者说只是美观不美观的问题,个人觉得其实并非完全如此。大家如果做过项目上线应该知道,使用history模式是需要后端配合的,后端具体做了啥?如下:

Apache

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>

nginx

1
2
3
location / {
  try_files $uri $uri/ /index.html;
}

原生 Node.js

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多弯一步路,这可能就是最根本的差别了。

本站所有文章、图片、资源等如无特殊说明或标注,均为来自互联网或者站长原创,版权归原作者所有;仅作为个人学习、研究以及欣赏!如若本站内容侵犯了原著者的合法权益,可联系我们进行处理,邮箱:343049466@qq.com
赞(2) 打赏
标签:

上一篇:

下一篇:

相关推荐

0 条评论关于"Vue Router中hash和history模式区别"

表情

最新评论

    暂无留言哦~~
谢谢你请我吃鸡腿*^_^*

支付宝扫一扫打赏

微信扫一扫打赏