视频1 视频21 视频41 视频61 视频文章1 视频文章21 视频文章41 视频文章61 推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37 推荐39 推荐41 推荐43 推荐45 推荐47 推荐49 关键词1 关键词101 关键词201 关键词301 关键词401 关键词501 关键词601 关键词701 关键词801 关键词901 关键词1001 关键词1101 关键词1201 关键词1301 关键词1401 关键词1501 关键词1601 关键词1701 关键词1801 关键词1901 视频扩展1 视频扩展6 视频扩展11 视频扩展16 文章1 文章201 文章401 文章601 文章801 文章1001 资讯1 资讯501 资讯1001 资讯1501 标签1 标签501 标签1001 关键词1 关键词501 关键词1001 关键词1501 专题2001
详解vue填坑之解决部分浏览器不支持pushState方法
2020-11-27 22:11:31 责编:小采
文档


前端使用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

    下载本文
    显示全文
    专题