vue填坑之解决部分浏览器不支持pushState方法

前端使用vue-router做单页面路由并开启history模式时,会碰到一个问题:部分低版本的手机浏览器、部分app以及IE9浏览器由于不支持pushState方法,会导致页面加载不出来。 解决这个问题的思路是:

  1. 当浏览器支持pushState方法时,开启history模式,不支持则开启hash模式
  2. 对链接做判断,当跳转的链接与路由模式不匹配时,则跳转至正确的链接
  3. 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
    }
复制代码

 

posted @   porter_代码工作者  阅读(107)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
历史上的今天:
2022-06-15 git 分布式系统,多url 设置
2018-06-15 移动端HTML5开发 选择方案
点击右上角即可分享
微信分享提示