uniapp 支持兩種路由跳轉模式:hash
和 history
。默認使用 hash
模式,使用 URL 的 hash 來模擬一個完整的 URL,於是當 URL 改變時,頁面不會重新加載。
注意:
history 模式部分瀏覽器器不支持,iOS微信內置瀏覽器無法觀測到URL變動,默認分享(不使用微信JSSDK的情況下)的鏈接為入口頁鏈接。
history 模式發行需要后台配置支持,詳見:history 模式的后端配置
配置 history
模式
如果不想要很丑的 hash,我們可以用路由的 history 模式,這種模式充分利用 history.pushState API 來完成 URL 跳轉而無須重新加載頁面。
const router = new VueRouter({
mode: 'history',
routes: [...]
})
當你使用 history 模式時,URL 就像正常的 url,例如 http://yoursite.com/user/id,也好看!
不過這種模式要玩好,還需要后台配置支持。因為我們的應用是個單頁客戶端應用,如果后台沒有正確的配置,當用戶在瀏覽器直接訪問 http://oursite.com/user/id 就會返回 404,這就不好看了。
所以呢,你要在服務端增加一個覆蓋所有情況的候選資源:如果 URL 匹配不到任何靜態資源,則應該返回同一個 index.html 頁面,這個頁面就是你 app 依賴的頁面。
后端配置例子
注意:下列示例假設你在根目錄服務這個應用。如果想部署到一個子目錄,你需要使用 Vue CLI 的 publicPath 選項 (opens new window)和相關的 router base property (opens new window)。你還需要把下列示例中的根目錄調整成為子目錄 (例如用 RewriteBase /name-of-your-subfolder/ 替換掉 RewriteBase /)。
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 (opens new window)](https://httpd.apache.org/docs/2.2/mod/mod_dir.html#fallbackresource "FallbackResource (opens new window)")
。
nginx
location / {
try_files $uri $uri/ /index.html;
}
比如 uniapp 的 H5 配置:
nginx 配置如下,只影響網站下某個目錄:
location ^~ /app/1ka_v2 {
try_files $uri $uri/ /app/1ka_v2/index.html;
}
參考鏈接
https://router.vuejs.org/zh/guide/essentials/history-mode.html#后端配置例子
https://uniapp.dcloud.io/collocation/manifest?id=h5-router