Vue Router HTML5 History 模式

vue-router 默認(rèn) hash 模式 —— 使用 URL 的 hash 來模擬一個(gè)完整的 URL,于是當(dāng) URL 改變時(shí),頁面不會(huì)重新加載。

如果不想要很丑的 hash,我們可以用路由的 history 模式,這種模式充分利用 history.pushState API 來完成 URL 跳轉(zhuǎn)而無須重新加載頁面。

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

當(dāng)你使用 history 模式時(shí),URL 就像正常的 url,例如 http://yoursite.com/user/id,也好看!

不過這種模式要玩好,還需要后臺(tái)配置支持。因?yàn)槲覀兊膽?yīng)用是個(gè)單頁客戶端應(yīng)用,如果后臺(tái)沒有正確的配置,當(dāng)用戶在瀏覽器直接訪問 http://oursite.com/user/id 就會(huì)返回 404,這就不好看了。

所以呢,你要在服務(wù)端增加一個(gè)覆蓋所有情況的候選資源:如果 URL 匹配不到任何靜態(tài)資源,則應(yīng)該返回同一個(gè) index.html 頁面,這個(gè)頁面就是你 app 依賴的頁面。

后端配置例子

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>

除了 mod_rewrite,你也可以使用 FallbackResource。

nginx

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

原生 Node.js

  const http = require('http')
  const fs = require('fs')
  const httpPort = 80

  http.createServer((req, res) => {
    fs.readFile('index.htm', 'utf-8', (err, content) => {
      if (err) {
        console.log('We cannot open "index.htm" file.')
      }

      res.writeHead(200, {
        'Content-Type': 'text/html; charset=utf-8'
     })

      res.end(content)
    })
  }).listen(httpPort, () => {
    console.log('Server listening on: http://localhost:%s', httpPort)
  })

基于 Node.js 的 Express

對于 Node.js/Express,請考慮使用 connect-history-api-fallback 中間件。

Internet Information Services (IIS)

  1. 安裝 IIS UrlRewrite
  2. 在你的網(wǎng)站根目錄中創(chuàng)建一個(gè) web.config 文件,內(nèi)容如下:
  <?xml version="1.0" encoding="UTF-8"?>
  <configuration>
    <system.webServer>
      <rewrite>
        <rules>
          <rule name="Handle History Mode and custom 404/500" stopProcessing="true">
            <match url="(.*)" />
            <conditions logicalGrouping="MatchAll">
              <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
              <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            </conditions>
            <action type="Rewrite" url="/" />
          </rule>
        </rules>
      </rewrite>
    </system.webServer>
  </configuration>

Caddy

  rewrite {
    regexp .*
    to {path} /
  }

Firebase 主機(jī)

在你的 firebase.json 中加入:

  {
    "hosting": {
      "public": "dist",
      "rewrites": [
        {
          "source": "**",
          "destination": "/index.html"
        }
      ]
    }
  }

警告

給個(gè)警告,因?yàn)檫@么做以后,你的服務(wù)器就不再返回 404 錯(cuò)誤頁面,因?yàn)閷τ谒新窂蕉紩?huì)返回 index.html 文件。為了避免這種情況,你應(yīng)該在 Vue 應(yīng)用里面覆蓋所有的路由情況,然后在給出一個(gè) 404 頁面。

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

或者,如果你使用 Node.js 服務(wù)器,你可以用服務(wù)端路由匹配到來的 URL,并在沒有匹配到路由的時(shí)候返回 404,以實(shí)現(xiàn)回退。更多詳情請查閱 Vue 服務(wù)端渲染文檔。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 介紹 vue-router是一個(gè)vue插件。其實(shí)質(zhì)是在location.hash、location.replace...
    AmazRan閱讀 1,653評論 0 6
  • 一、前言 要學(xué)習(xí)vue-router就要先知道這里的路由是什么?為什么我們不能像原來一樣直接用 標(biāo)簽編寫鏈接哪?...
    浪里行舟閱讀 68,148評論 12 203
  • 隨著前端應(yīng)用的業(yè)務(wù)功能起來越復(fù)雜,用戶對于使用體驗(yàn)的要求越來越高,單面(SPA)成為前端應(yīng)用的主流形式。大型單頁應(yīng)...
    bayi_lzp閱讀 5,994評論 0 2
  • 一、概念闡述 對于 Vue 這類漸進(jìn)式前端開發(fā)框架,為了構(gòu)建 SPA(單頁面應(yīng)用),需要引入前端路由系統(tǒng),這也就是...
    frog78閱讀 7,265評論 0 6
  • 用vue-cli開發(fā)的項(xiàng)目在開發(fā)完打包之后想在本地預(yù)覽要怎么做呢?這里要根據(jù)你的路由模式來分兩種情況 1. his...
    liwuwuzhi閱讀 13,717評論 6 16

友情鏈接更多精彩內(nèi)容