前端微服务qiankun入门之hash路由实践

完整代码地址在microfrontend-learning 

1. 主应用改造

修改activeRule

如: 

[
  {
    name: "ReactMicroApp",
    entry: process.env.VUE_APP_REACT_MICRO_APP,
    container: "#frame",
    activeRule: "/#/microApp/react",
  },
  {
    name: "VueMicroApp",
    entry: process.env.VUE_APP_VUE_MICRO_APP,
    container: "#frame",
    activeRule: "/#/microApp/vue",
  }
]

路由部分修改

2. vue子应用修改 

router修改

import Home from '@/pages/home/index.vue';

let prefix = window.__POWERED_BY_QIANKUN__ ? '/microApp/vue/' : '/';

const routes = [
  {
    path: prefix == '/' ? prefix : prefix.substring(0, prefix.length - 1),
    name: 'Home',
    component: Home
  },
  {
    path: prefix + 'about',
    name: 'About',
    component: () => import('@/pages/about/index.vue')
  }
]

export default routes;

修改main.js中VueRouter mode及增加监听beforeEach事件

//...省略

let instance = null
let router = null

/**
 * 渲染函数
 * 两种情况:主应用生命周期钩子中运行 / 微应用单独启动时运行
 */
function render() {
  // 在 render 中创建 VueRouter,可以保证在卸载微应用时,移除 location 事件监听,防止事件污染
  router = new VueRouter({
    // 运行在主应用中时,添加路由命名空间 /vue
    // base: window.__POWERED_BY_QIANKUN__ ? "/vue" : "/",
    // mode: "history",
    routes,
  });
  if (window.__POWERED_BY_QIANKUN__) {
    router.beforeEach((to, from, next) => {
      if (!to.path.includes("/microApp")) {
        next({
          path: "/microApp/vue" + (to.path == "/" ? "" : to.path) 
        })
      } else {
        next()
      }
    })
  }

  // 挂载应用
  instance = new Vue({
    router,
    render: (h) => h(App),
  }).$mount("#app")
}

// 独立运行时,直接挂载应用
if (!window.__POWERED_BY_QIANKUN__) {
  render()
}

//...省略

3. React子应用改造

修改App.js

参考资料:

https://qiankun.umijs.org/zh/guide/tutorial

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值