前端使用vue-router做單頁面路由并開啟history模式時,會碰到一個問題:部分低版本的手機瀏覽器、部分app以及IE9瀏覽器由于不支持pushState方法,會導致頁面加載不出來。 解決這個問題的思路是:
以下為具體實現方法:
判斷使用何種路由模式
let isHans = typeof (history.pushState) === 'function';let mode = isHans?'history':'hash';
判斷請求鏈接
每次進入路由時,判斷請求鏈接跳轉的鏈接與路由模式不匹配時,則跳轉至正確的鏈接
router.beforeEach(async (to, from, next) => { let toPath = to.fullPath,host = 'http://abc.cn'; let url = host + toPath; let reUrl = url; if(isHans && url.indexOf(`${host}/#/`) >-1){ reUrl = url.replace(`${host}/#/`,`${host}/car-insurance/`); } if(!isHans && url.indexOf(`${host}/#/`) === -1){ reUrl = url.replace(`${host}/car-insurance/`,`${host}/#/`); reUrl = reUrl.replace(`${host}/`,`${host}/#/`); } if(reUrl !== url){ window.location.replace(reUrl); return }
配置nginx
server { listen 80; listen 443; server_name abc.cn; root /data/html; index index.html index.htm index.json; access_log off ; set $isIndex 1; ##判斷IE6-8 if ($http_user_agent ~* "MSIE [6-8].[0-9]") { rewrite .* /static/ie8.html break; } if ( $request_uri ~* "/(favicon.ico|index.js|root.txt|jd_root.txt)$" ) { #不跳轉到index.html set $isIndex 0; } if ( $request_uri ~* "/static/" ) { #不跳轉到index.html set $isIndex 0; } if ($isIndex = 1 ){ set $inIndexJS 0; rewrite .* /index.html; break; }}a
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答