前端路由的hash和history模式

1. hash模式

监听window.onhashChange事件,通过event的oldUrl和newUrl来做一些切换操作

2. history模式

监听window.onpopstate事件,来在路由切换时候做一些操作

常用的state api有:

history.pushState(data,title,url) //入栈一条历史记录
history.replaceState(data,title,url) //替换一条历史记录
history.state //获取pushState和replaceState传递的data

3. history模式未知路由处理

pushState操作本身,不会触发浏览器请求后端,所以只是前端的一个操作。
但是,切换地址后,用户可能会刷新页面,或使用后退,前进按钮,此时,后端路由如果不处理,就会返回404。
后端需要加上路由处理,覆盖所有未知的路由,具体如下:

nginx

{
   try_files $uri $uri/ /index.html; //无匹配时候,总是返回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>

同时,前端路由,也应该处理404的情况,在pushState输入一个错误路由时候,给出一个提示。

原文地址:https://www.cnblogs.com/mengff/p/12779450.html