IE 下路由变化,页面不刷新(window.location.href/hash 失效)

1,924 阅读1分钟

项目背景

框架:使用微前端框架 - qiankun + Vue

模块:首页(#/portal-home/*)、搜索页(#/search/*)等

问题描述

模块间跳转正常,如首页 #/portal-home/index 跳转至搜索页 #/search/index

window.location.hash = '#/search/index'

模块内跳转异常,如首页 #/portal-home/index 跳转至首页客服 #/portal-home/service

window.location.hash = '#/portal-home/service'
or
window.location.href = '/portal-home/service'

异常描述:地址栏 url 已更新为客服路由 /portal-home/service,但是页面不刷新,仍显示首页 #/portal-home/index,手动刷新后显示客服页面

异常浏览器:IE11、360 兼容模式

异常原因:未知

解决方法

受微前端限制,不同模块间跳转无法使用 this.$router.push 。因此,判断是否为同一模块,是,则使用 this.$router.push;否,则使用 window.location.hash

this.$router.push 原理:源码中 hash 模式的 push 方法在支持 pushState 的浏览器中使用 window.history.pushState 进行路由跳转。

const path = '/portal-home/service'
this.$router.push(path)
等同于
// Vue-Router 源码
window.history.pushState({ key: Date.now().toFixed(3) }, '', path)

遗留问题

IE 在部分情况下(模块内跳转),使用 window.location.hash/href 跳转页面,仅路由更新,页面不更新原因?

为什么使用 window.history.pushState 能解决以上问题?