參考資料:
- https://juejin.cn/post/7127143415879303204#heading-11
- https://blog.csdn.net/qq_28641023/article/details/120328826
理解單頁面應用
- 單頁面應用是指我們的服務只有一個index.html的靜態文件,前端生成後,丟到服務器上面。用戶訪問不同的頁面,實際上都是訪問index.html。
- index.html只請求了一次,後面頁面跳轉都不會再請求index.html
Vue-router中的路由模式
對比項 | hash模式 | history模式 |
---|---|---|
url變化 | # | 無 |
刷新當前頁面是否會404 | 無 | 404(nginx),解決方法:配置nginx,不管什麼pathname都指向index.html |
是否需要後端配合 | 不需要 | 需要 |
hash路由
實現基礎:瀏覽器暴露出來的「hashchange」
方法
原理:監聽hash的變化,渲染不同的組件代碼。
瀏覽器暴露現成方法的hashchange
,在hash改變時,觸發該事件,在監聽事件的回調方法中執行組件的顯示隱藏邏輯。
window.addEventListener('hashchange', this.refresh, false);
refresh(){
// hash改變時,執行這裏...
}
history路由
實現基礎:history路由模式的實現歸功於HTML5暴露提供history
全局對象,同時還暴露了常用的方法如:
-
window.history.go
-
window.history.forward
-
window.history.back
-
window.history.pushState 可以將給定的數據壓入到瀏覽器會話歷史棧中
-
window.history.replaceState 將當前的url替換成指定的數據
原理:
主要依賴pushState
、replaceState
實現的,都會改變當前顯示的url,但不會刷新頁面。通過監聽URL的變化,實現前端渲染邏輯的處理。
window.addEventListener('popState', e=> {
// 監聽自定義事件,拿到上面的pushState的參數,做出相應的頁面渲染
})