有關路由實例
參考學習:https://www.cnblogs.com/SamWeb/p/6610733.html
vue-router路由模式:
參考學習:https://www.cnblogs.com/goloving/p/9147551.html
vue-router 有 3 種路由模式:hash、history、abstract,對應的源碼以下所示:html
switch (mode) { case 'history': this.history = new HTML5History(this, options.base) break case 'hash': this.history = new HashHistory(this, options.base, this.fallback) break case 'abstract': this.history = new AbstractHistory(this, options.base) break default: if (process.env.NODE_ENV !== 'production') { assert(false, `invalid mode: ${mode}`) } }
其中,3 種路由模式的說明以下:前端
hash: 使用 URL hash 值來做路由。支持全部瀏覽器,包括不支持 HTML5 History Api 的瀏覽器;
history 依賴 HTML5 History API 和服務器配置。具體能夠查看 HTML5 History 模式;
abstract : 支持全部 JavaScript 運行環境,如 Node.js 服務器端。若是發現沒有瀏覽器的 API,路由會自動強制進入這個模式.vue
二、能說下 vue-router 中經常使用的 hash 和 history 路由模式實現原理嗎?
(1)hash 模式的實現原理
早期的前端路由的實現就是基於 location.hash 來實現的。其實現原理很簡單,location.hash 的值就是 URL 中 # 後面的內容。好比下面這個網站,它的 location.hash 的值爲 ‘#search’:
https://www.word.com#search
複製代碼hash 路由模式的實現主要是基於下面幾個特性:
URL 中 hash 值只是客戶端的一種狀態,也就是說當向服務器端發出請求時,hash 部分不會被髮送;
hash 值的改變,都會在瀏覽器的訪問歷史中增長一個記錄。所以咱們能經過瀏覽器的回退、前進按鈕控制hash 的切換;
能夠經過 a 標籤,並設置 href 屬性,當用戶點擊這個標籤後,URL 的 hash 值會發生改變;或者使用 JavaScript 來對 loaction.hash 進行賦值,改變 URL 的 hash 值;
咱們可使用 hashchange 事件來監聽 hash 值的變化,從而對頁面進行跳轉(渲染)。web
(2)history 模式的實現原理
HTML5 提供了 History API 來實現 URL 的變化。其中作最主要的 API 有如下兩個:history.pushState() 和 history.repalceState()。這兩個 API 能夠在不進行刷新的狀況下,操做瀏覽器的歷史紀錄。惟一不一樣的是,前者是新增一個歷史記錄,後者是直接替換當前的歷史記錄,以下所示:
window.history.pushState(null, null, path);
window.history.replaceState(null, null, path);
複製代碼history 路由模式的實現主要基於存在下面幾個特性:vue-router
pushState 和 repalceState 兩個 API 來操做實現 URL 的變化 ;
咱們可使用 popstate 事件來監聽 url 的變化,從而對頁面進行跳轉(渲染);
history.pushState() 或 history.replaceState() 不會觸發 popstate 事件,這時咱們須要手動觸發頁面跳轉(渲染)。瀏覽器