关于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