1. 各服务的路由使用的都是hash模式
2. 每一个子服务都有各自的pathname
3. 路由的跳转使用的都是$router.push
4. 多点几次浏览器的回退按钮
经过上面的一系列操作后在主服务的路由前置守卫中获取到的to.path值竟然为undefined。
网上查了一波,也不知道是为啥,看到篇文章说不要使用$router.push跳转路由,可以使用window.history.pushState,测试了下确实可以,然后就写了个方法去替换了路由的push函数
import qs from 'querystring'
const baseName = '/store/#' //各子服务的pathname+'#'
export function $_routerPush(routerLocation: any, qianKunTag: boolean, router: any) {
if (qianKunTag) {
let gotoPath = baseName
if (Object.prototype.toString.call(routerLocation) === '[object String]') {
gotoPath += routerLocation
} else {
const { path, query } = routerLocation
gotoPath += path
query && (gotoPath += `?${qs.stringify(query)}`)
}
window.history.pushState({}, '', gotoPath)
} else {
if (Object.prototype.toString.call(routerLocation) === '[object String]') {
router && router.push(routerLocation)
} else {
const { name, path, query, params } = routerLocation
router && router.push({ name, path, query, params })
}
}
}
export function $_routerReplace(routerLocation: any, qianKunTag: boolean, router: any) {
if (qianKunTag) {
let gotoPath = baseName
if (Object.prototype.toString.call(routerLocation) === '[object String]') {
gotoPath += routerLocation
} else {
const { path, query } = routerLocation
gotoPath += path
query && (gotoPath += `?${qs.stringify(query)}`)
}
window.history.replaceState({}, '', gotoPath)
} else {
if (Object.prototype.toString.call(routerLocation) === '[object String]') {
router && router.replace(routerLocation)
} else {
const { name, path, query, params } = routerLocation
router && router.replace({ name, path, query, params })
}
}
}
然后将这两个函数挂到vue实例上
import { $_routerPush, $_routerReplace } from './child-config'
let app: ReturnType<typeof createApp>
function render(qiankuntag: boolean, props: any = {}) {
const { container } = props
app = createApp(App)
app.use(component)
initElement(app)
app
.use(router)
.use(store, key)
.mount(container ? container.querySelector('#app') : '#app')
app.config.globalProperties.$_routerPush = (path: any) => {
$_routerPush(path, qiankuntag, router)
}
app.config.globalProperties.$_routerReplace = (path: any) => {
$_routerReplace(path, qiankuntag, router)
}
}
当然这里是用的vue3的实例挂载,vue2就是挂在Vue实例的原型上就行
Vue.prototype.$_routerPush = (path) => {
$_routerPush(path, qiankuntag, router)
}
Vue.prototype.$_routerReplace = (path) => {
$_routerReplace(path, qiankuntag, router)
}
每个子服务都需使用以上函数,最后就是将$router.push全局替换成$_routerPush即可。