前端路由的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輸入一個錯誤路由時候,給出一個提示。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM