vue-router 原理
執行過程:當用戶點選 router-link 標籤時,會去尋找它的 to 屬性, 它的 to 屬性和 js 中配置的路徑{ path: '/home', component: Home}path 一一對應,從而找到了匹配的元件, 最後把元件渲染到標籤所在的地方。
vue-router 是 vue.js 框架的路由外掛,它是通過 mode 這一引數控制路由的實現模式的。
const router = new VueRouter({ // HTML5 history 模式 mode: 'history', base: process.env.NODE_ENV === 'production' ? process.env.PROXY_PATH : '', routes, })
原始碼分析
var VueRouter = function VueRouter (options) { if ( options === void 0 ) options = {}; this.app = null; this.apps = []; this.options = options; this.beforeHooks = []; this.resolveHooks = []; this.afterHooks = []; // 建立 matcher 匹配函式 this.matcher = createMatcher(options.routes || [], this); // 根據 mode 例項化具體的 History,預設為'hash'模式 var mode = options.mode || 'hash'; // 通過 supportsPushState 判斷瀏覽器是否支援'history'模式 // 如果設定的是'history'但是如果瀏覽器不支援的話,'history'模式會退回到'hash'模式 // fallback 是當瀏覽器不支援 history.pushState 控制路由是否應該回退到 hash 模式。預設值為 true。 this.fallback = mode === 'history' && !supportsPushState &&options.fallback !== false; if (this.fallback) { mode = 'hash'; } if (!inBrowser) { // 不在瀏覽器環境下執行需強制為'abstract'模式 mode = 'abstract'; } this.mode = mode; // 根據不同模式選擇例項化對應的 History 類 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: { assert(false, ("invalid mode: " + mode)); } } };
history 模式
VueRouter.prototype.init = function init (app /* Vue component instance */) { ... var history = this.history; // 根據history的類別執行相應的初始化操作和監聽 if (history instanceof HTML5History) { history.transitionTo(history.getCurrentLocation()); } else if (history instanceof HashHistory) { var setupHashListener = function () { history.setupListeners(); }; history.transitionTo( history.getCurrentLocation(), setupHashListener, setupHashListener ); } history.listen(function (route) { this$1.apps.forEach(function (app) { app._route = route; }); }); };
- 在初始化對應的history之前,會對mode做一些校驗:若瀏覽器不支援HTML5History方式(通過supportsPushState變數判斷),則mode設為hash;若不是在瀏覽器環境下執行,則mode設為abstract;
- VueRouter類中的onReady(),push()等方法只是一個代理,實際是呼叫的具體history物件的對應方法,在init()方法中初始化時,也是根據history物件具體的類別執行不同操作
pushState和replaceState兩種方法的共同特點:當呼叫他們修改瀏覽器歷史棧後,雖然當前url改變了,但瀏覽器不會立即傳送請求該url,這就為單頁應用前端路由,更新檢視但不重新請求頁面提供了基礎。
而history模式則將url修改的就和正常請求後端的url一樣(history不帶#)
http://oursite.com/user/id
如果這種向後端傳送請求的話,後端沒有配置對應/user/id的get路由處理,會返回404錯誤。
你要在服務端增加一個覆蓋所有情況的候選資源:如果 URL 匹配不到任何靜態資源,則應該返回同一個 index.html 頁面,這個頁面就是你 app 依賴的頁面
給個警告,因為這麼做以後,你的伺服器就不再返回 404 錯誤頁面,因為對於所有路徑都會返回 index.html 檔案。為了避免這種情況,你應該在 Vue 應用裡面覆蓋所有的路由情況,然後在給出一個 404 頁面。