溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

詳解vue填坑之解決部分瀏覽器不支持pushState方法

發(fā)布時間:2020-09-30 17:31:40 來源:腳本之家 閱讀:188 作者:Jiang Xueyang 欄目:web開發(fā)

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI