詳解vue填坑之解決部分瀏覽器不支持pushState方法
前端使用vue-router做單頁面路由并開啟history模式時(shí),會碰到一個(gè)問題:部分低版本的手機(jī)瀏覽器、部分app以及IE9瀏覽器由于不支持pushState方法,會導(dǎo)致頁面加載不出來。 解決這個(gè)問題的思路是:
- 當(dāng)瀏覽器支持pushState方法時(shí),開啟history模式,不支持則開啟hash模式
- 對鏈接做判斷,當(dāng)跳轉(zhuǎn)的鏈接與路由模式不匹配時(shí),則跳轉(zhuǎn)至正確的鏈接
- nginx對域名下的路徑訪問均重寫向至index.html
以下為具體實(shí)現(xiàn)方法:
判斷使用何種路由模式
let isHans = typeof (history.pushState) === 'function'; let mode = isHans?'history':'hash';
判斷請求鏈接
每次進(jìn)入路由時(shí),判斷請求鏈接跳轉(zhuǎn)的鏈接與路由模式不匹配時(shí),則跳轉(zhuǎn)至正確的鏈接
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)$" ) { #不跳轉(zhuǎn)到index.html set $isIndex 0; } if ( $request_uri ~* "/static/" ) { #不跳轉(zhuǎn)到index.html set $isIndex 0; } if ($isIndex = 1 ){ set $inIndexJS 0; rewrite .* /index.html; break; } }a
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
基于vue-cli創(chuàng)建的項(xiàng)目的目錄結(jié)構(gòu)及說明介紹
下面小編就為大家分享一篇基于vue-cli創(chuàng)建的項(xiàng)目的目錄結(jié)構(gòu)及說明介紹,具有很好的參考價(jià)值,希望對大家有所幫助2017-11-11Vuejs入門教程之Vue生命周期,數(shù)據(jù),手動掛載,指令,過濾器
本篇文章主要介紹了Vuejs入門教程之Vue生命周期,數(shù)據(jù),手動掛載,指令,過濾器的相關(guān)知識。具有很好的參考價(jià)值。下面跟著小編一起來看下吧2017-04-04Vue使用ElementUI動態(tài)修改table單元格背景顏色或文本顏色
本文主要介紹了Vue使用ElementUI動態(tài)修改table單元格背景顏色或文本顏色,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02