vue路徑Url帶/#/去除方法


在router->index.js中mode類型默認為hash,修改為history

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

 

除此之外,需要服務端配合,主要因為這種模式利用history.pushState API 來完成 URL 跳轉而無須重新加載頁面。當刷新頁面的時候就會404了。

 

后端配置例子

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 中間件。

資源搜索網站大全 http://www.szhdn.com

Internet Information Services (IIS)

安裝 IIS UrlRewrite

在你的網站根目錄中創建一個 web.config 文件,內容如下:

<?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 主機

在你的 firebase.json 中加入:

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

警告

給個警告,因為這么做以后,你的服務器就不再返回 404 錯誤頁面,因為對於所有路徑都會返回 index.html 文件。為了避免這種情況,你應該在 vue 應用里面覆蓋所有的路由情況,然后在給出一個 404 頁面。

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

 

或者,如果你使用 Node.js 服務器,你可以用服務端路由匹配到來的 URL,並在沒有匹配到路由的時候返回 404,以實現回退。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM