重写window.open && location
需求前提: 在使用 对项目进行集成之后,项目的路由中会有当前项目的name开头,这就导致,页面中使用a标签,对路由进行跳转时,会出现当前页面空白的问题. 如下图所示的几种跳转方式 1. 完整路径: http://www.baidu.com 当这种地址时,当前可以打开新页面直接跳转 2. router地址 /test2/test21, 若是在单系统中,跳转的地址为localhost:8080/test2/test21 3. 通过this.router.resolve()拿到的地址 4. <a :href="url"></a> 通过href的地址跳转 上面四种情况,在单环境下确实可以完整打开,但是在qiankun下,只有1和3可以完整打开,2和4 均缺少当前通过qiankun集成的appName前缀. 因此 期望单环境 localhost:8080/test2/test21 ; qiankun的集成环境为localhost:8080/appName/test2/test21 从上面可以看出,使用方式3确实可以解决当前路由跳转的问题,但是既然时集成的环境,必然涉及到多个系统,若是对每个环境中使用其他方式的跳转进行修改的话,很明显时间成本很大,因此,决定对window.open进行重写,这样的话;
重写逻辑 (放到main.js中)
该方式也适用于当域名被占用,而把项目放在二级域名下,给路由地址携带当前的base
/** 使用原生window.open、window.location.href在集成环境中时,应用名前缀没有带上问题 **/
// 获取当前集成的环境名
const appPath = process.env.APP_INFO.path
window.open = (function (_open) {
return function () {
console.log(arguments, "--- 集成环境:window.open---", appPath)
if (window.$isPoweredByApp) {
// 这里是在集成时,给了一个环境的唯一标识
// 集成环境
const url = arguments[0]
if (url.indexOf(appPath) !== 0 && !(url.indexOf(http://) === 0 || url.indexOf(https://) === 0)) {
arguments[0] = appPath + url
}
}
_open.apply(this, arguments)
}
}(window.open))
// 重写location.href,由于无法复盖它,所以使用window.$location.href代替跳转
window.$location = new Proxy(Object.create(window.location), {
set (target, key, value) {
if (key === href && window.$isPoweredByApp) {
// 集成环境
if (value.indexOf(appPath) !== 0 && !(value.indexOf(http://) === 0 || value.indexOf(https://) === 0)) {
return window.location[key] = appPath + value
}
}
return window.location[key] = value
}
})
