HTML5 History 模式

vue-router 默認 hash 模式 —— 使用 URL 的 hash 來模擬一個完整的 URL,因而當 URL 改變時,頁面不會從新加載。html

若是不想要很醜的 hash,咱們能夠用路由的 history 模式,這種模式充分利用 history.pushState API 來完成 URL 跳轉而無須從新加載頁面。vue

const router = new VueRouter({ mode: 'history', routes: [...] }) 

當你使用 history 模式時,URL 就像正常的 url,例如 http://yoursite.com/user/id,也好看!node

不過這種模式要玩好,還須要後臺配置支持。由於咱們的應用是個單頁客戶端應用,若是後臺沒有正確的配置,當用戶在瀏覽器直接訪問 http://oursite.com/user/id 就會返回 404,這就很差看了。nginx

因此呢,你要在服務端增長一個覆蓋全部狀況的候選資源:若是 URL 匹配不到任何靜態資源,則應該返回同一個index.html 頁面,這個頁面就是你 app 依賴的頁面。git

後端配置例子

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> 

nginx

location / { try_files $uri $uri/ /index.html; } 

Node.js (Express)

https://github.com/bripkens/connect-history-api-fallbackgithub

警告

給個警告,由於這麼作之後,你的服務器就再也不返回 404 錯誤頁面,由於對於全部路徑都會返回 index.html 文件。爲了不這種狀況,你應該在 Vue 應用裏面覆蓋全部的路由狀況,而後在給出一個 404 頁面。vue-router

const router = new VueRouter({ mode: 'history', routes: [ { path: '*', component: NotFoundComponent } ] }) 

或者,若是你是用 Node.js 做後臺,可使用服務端的路由來匹配 URL,當沒有匹配到路由的時候返回 404,從而實現 fallback。express

相關文章
相關標籤/搜索