vue-router默認的路由模式是hash,我們要去掉url中的#需要將路由模式切換為history
const router = new VueRouter({ mode: 'history', ... })
這樣子,url中的#就可以去掉了,在開發環境下不會出問題,部署上線后點擊正常,但是...你一旦手動點擊瀏覽器的刷新按鈕,頁面顯示nginx的404頁面。
怎么解決呢?在vue-router官網有說明:這種模式還需要后台配置支持。因為我們的應用是個單頁客戶端應用,如果后台沒有正確的配置,當用戶在瀏覽器直接訪問 http://oursite.com/user/id
就會返回 404,這就不好看了。
所以呢,你要在服務端增加一個覆蓋所有情況的候選資源:如果 URL 匹配不到任何靜態資源,則應該返回同一個 index.html
頁面,這個頁面就是你 app 依賴的頁面。我們線上的服務器用的是nginx,需要改為下面的配置:
# 項目部署在服務器/test目錄下(訪問地址:http://www.a.com/test)
location ^~/test {
alias D:/project/card-web/code/dist/; try_files $uri $uri/ @card; access_log logs/card_web.access.log ; error_log logs/card_web.error.log ; } location @card { rewrite ^/(test)/(.+)$ /$1/index.html last; }
# 項目部署在服務器/下(訪問地址:http://www.a.com)
location / { root D:/project/card-web/code/dist/; index index.html index.htm; try_files $uri $uri/ /index.html; }
這樣子,無論你怎么刷新頁面都不會報404了。。。賊開心。。。
然而,點進去一個二級路由發現,頁面中的圖片全都沒有加載成功。。。vue-router官網有這么一句話:要注意,以 /
開頭的嵌套路徑會被當作根路徑。 這讓你充分的使用嵌套組件而無須設置嵌套的路徑。
我頁面中是這么寫的:
<img :src="`./static/image/real-time-monitoring/online-line.png`"
alt="" class="line-img line-rotation">
f12后發現,瀏覽器的請求路徑是:
Request URL: http://localhost:8080/cardapp/card/static/image/real-time-monitoring/online-line.png
我的路由:
{ path: '/cardapp', component: CardApp, name: 'cardapp', children:[ { path: 'card', component: add} ] }
解決辦法:
<img :src="`/static/image/real-time-monitoring/online-line.png`"
alt="" class="line-img line-rotation">
原因:這圖片處在嵌套路由下,這個嵌套路由以 / 開頭,會被當做根路徑,之前寫的相對路徑會拼接到這個嵌套路由下,所有會出現圖片路徑會加上當前路由了。