详解vue填坑之解决部分浏览器不支持pushState方法
2019/6/27 7:50:44
本文主要是介绍详解vue填坑之解决部分浏览器不支持pushState方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
前端使用vue-router做单页面路由并开启history模式时,会碰到一个问题:部分低版本的手机浏览器、部分app以及IE9浏览器由于不支持pushState方法,会导致页面加载不出来。 解决这个问题的思路是:
- 当浏览器支持pushState方法时,开启history模式,不支持则开启hash模式
- 对链接做判断,当跳转的链接与路由模式不匹配时,则跳转至正确的链接
- nginx对域名下的路径访问均重写向至index.html
以下为具体实现方法:
判断使用何种路由模式
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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持找一找教程网。
这篇关于详解vue填坑之解决部分浏览器不支持pushState方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-21Vue3教程:新手入门与实战指南
- 2024-09-21VueRouter4教程:入门与实践指南
- 2024-09-21Vuex4项目实战:新手入门教程
- 2024-09-21Vue3项目实战:初学者指南
- 2024-09-21Vue3项目实战:从零开始构建你的第一个Vue3应用
- 2024-09-21VueRouter4项目实战入门教程
- 2024-09-21Vue3入门:新手必读指南
- 2024-09-20Vue3教程:初学者快速入门指南
- 2024-09-20Vue资料入门教程:从零开始学习Vue.js
- 2024-09-20Vuex4入门教程:轻松掌握Vue状态管理