關於vue-router中點擊瀏覽器前進后退地址欄路由變了但是頁面沒跳轉


情景:

在進行正常頁面跳轉操作后(頁面A跳轉到頁面B),點擊瀏覽器的左上角的‘后退’按鈕,點擊后,可以看到url地址已經發生了變化(url由頁面B變為頁面A),hash值也已經是上一頁的路由,但是瀏覽器顯示的內容卻沒有發生變化(依舊是頁面B)。

沒有任何報錯(頁面A和頁面B無任何js錯誤或者兼容性錯誤)。

若有錯誤也會導致頁面跳轉不成功,頁面依舊是當前頁面,但是控制台會報ERROR。

但是頁面按瀏覽器刷新按鈕后,一切又恢復了正常。真的讓人很頭疼,IE,Chrome,fireFox,Edge都是這樣

 

過程:

百度查了很多,就是hash模式導致的,所以重新出發下hashchange事件解決了問題,

具體如下:

 

本地路由配置:

 1 const baseRoute = [  2   { path: '/login', name: 'login', component: Login },  3   { path: '/404', name: 'page404', component: page404 },  4   {path: '/', redirect: '/index', component: Layout, name: 'dashboard'},  5  {  6     path: '/',  7     redirect: '/index',  8  component: Layout,  9  children: [ 10  { 11         path: 'index', 12         name: 'index', 13  component: xxxx, 14  meta: { 15           title: 'xxx', 16           icon: ''
17  } 18  }, 19  { 20         path: 'project', 21         name: 'project', 22  component: xxxx, 23  meta: { 24           dynamic: true, // 動態面包屑標題
25           title: ''
26  } 27  }, 28  { 29         path: 'project/onlineEquip/debug/:id', 30         name: 'debug', 31  component: Debug, 32  meta: { 33           title: '調試', 34           level: 3, 35           hidden: true
36  } 37  }, 38  { 39         path: 'project/onlineEquip/detail/:id', 40         name: 'detail', 41  component: Detail, 42  meta: { 43           title: 'xxx', 44           level: 3, 45           hidden: true
46  } 47  }, 48  { 49         path: 'project/log', 50         name: 'log', 51  component: Log, 52  meta: { 53           title: '日志', 54           level: 2, 55           hidden: true
56  } 57  }, 58  { 59         path: 'project/myPhyModel', 60         name: 'CreateModel', 61  component: xxxxx, 62  meta: { 63           title: 'xxxxx', 64           level: 2, 65           hidden: true
66  } 67  }, 68  { 69         path: 'project/myPhyModel/detail', 70         name: 'ModelDetail', 71  component: xxx, 72  meta: { 73           title: '詳情', 74           level: 3, 75           hidden: true
76  } 77  } 78  ] 79  }, 80  { 81     path: '*', // 頁面不存在的情況下會跳到404頁面
82     redirect: '/404', 83     name: 'notFound', 84     hidden: true
85  } 86 ] 87 const router = new Router({ 88   routes: baseRoute    // 這里默認是hash模式
89 }) 90 
91 export default router
View Code

 

解決辦法:

1、vue-router HTML5 History 模式  可以設置為history 模式解決問題

2、在hash模式的前提下來解決, 

  a、首先學習下hash模式的url相關知識 

  

  

  b、對,就是通過onhashchange 事件來解決這個bug

    APP.vue入口中:

    

mounted () {
    // 檢測瀏覽器路由改變頁面不刷新問題,hash模式的工作原理是hashchange事件
    window.addEventListener('hashchange', () => {
      let currentPath = window.location.hash.slice(1)
      if (this.$route.path !== currentPath) {
        this.$router.push(currentPath)
      }
    }, false)
  },

  

  重新刷新一遍路由,問題就可以解決啦!

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM