hash 模式和 history 模式的区别
表现
- hash 模式: juejin.cn/#/drafts?id…
- history 模式:juejin.cn/drafts/2565…
原理
- hash 模式: 基于锚点和
onhashchange事件 - history 模式:基于
HTML5的History API
当我们点击 router-link 超链接时,实际就调用了 pushState 这个 API,这个方法会改变浏览器地址栏中的地址,并将这个地址保存到浏览记录中,但不会发送请求,所以这一系列的操作都是在客户端完成的。
history.pushState()
history.replaceState()
默认 hash 模式
VueRouter 默认是 hash 模式的,如果要使用 history 模式,需要配置:
new VueRouter({
mode: 'history',
routes
})
history 模式需要服务器的支持
在单页面应用中,服务器上只存放了一个 index.html,所以当我们访问 test.cn/login 时,是找不到这样的页面的,所以需要在服务器上配置除静态资源外的地址都返回单页面应用的index.html。
VueCli
VueCli 自带的 web 服务器已经配置好了对 history 模式的支持。 当我们使用 node.js 和 nginx 时,如果没有配置 history 模式,在首页点击链接跳转会成功,因为调用的 pushState 仅在客户端操作,但是在首页以外的页面进行刷新时,就会报错页面找不到。
node.js
需要导入处理 history 的模块:connect-history-api-fallback
nginx
start nginx 启动 // 默认在 80 端口启动
nginx -s reload 重启
nginx -s stop 停止
下载 nginx 后,我们主要要关注一下目录下的 nginx.exe / conf / html
- 将打包好的项目放到 html 文件夹,用于存储我们的网站(含有 index.html)
- 修改 conf/nginx.conf 支持 history 模式
server {
listen 80; // 端口号
server_name localhost; // 域名
location / {
root html; // 项目根目录
index index.html index.htm; // 默认首页
try_files $uri $uri/ /index.html
}
}
在配置文件中添加 try_files 可以支持 history 模式,当发送请求找文件时,先找对应 uri,再找对应 uri 的目录,最后使用 index.html。
此时,当我访问 localhost/login 页面的时候,就会返回 index.html,浏览器接收到 index.html 后,会再去判断路由地址 login 对应的组件。