詳解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 的 Electron 項(xiàng)目搭建過程圖文詳解
這篇文章主要介紹了基于 Vue 的 Electron 項(xiàng)目搭建過程,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07
vue 自動(dòng)檢測手機(jī)端響應(yīng)式布局的五種實(shí)現(xiàn)
本文主要介紹了vue自動(dòng)檢測手機(jī)端響應(yīng)式布局,可以通過結(jié)合 CSS 媒體查詢、Vue 的動(dòng)態(tài)數(shù)據(jù)綁定、適當(dāng)?shù)牡谌綆?、PostCSS 插件以及正確的視口設(shè)置實(shí)現(xiàn),感興趣的可以了解一下2024-07-07
vue用h()函數(shù)創(chuàng)建Vnodes的實(shí)現(xiàn)
Vue提供了一個(gè)h()函數(shù)用于創(chuàng)建vnodes,本文就來介紹一下vue用h()函數(shù)創(chuàng)建Vnodes的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下2024-01-01

