微前端qiankun接入vue2&vue3项目

官方文档

接入vue2项目和vue3项目

对应路由模式分别是hashhistory

主应用

主应用是基于vue3开发的一个门户网站,仅有登录以及门户列表。

基于路由配置方式

通过将微应用关联到一些 url 规则的方式,实现当浏览器 url 发生变化时,自动加载相应的微应用的功能。

  1. config下面存放微应用的配置信息,代码如下:

        
        
        
        export const getQiankunConfig = (props = {}) => {
          return {
            subApps: [
              {
                name: "xxx-wms", 
                entry: "//192.168.1.40:8990/", 
                container: "#sub-container", 
                activeRule: "/xxx/wms", 
                props 
              },
              {
                name: "xxx-report", 
                entry: "//192.168.1.40:9527/#/", 
                container: "#sub-container", 
                activeRule: "/xxx/report", 
                props 
              },
            ]
          };
        };
    
  2. index放初始化函数以及一些其他需要配置和操作

    
    import { registerMicroApps } from "qiankun";
    import { getQiankunConfig } from "./configs";
    import { getToken } from "@/plugins/cache";
    import useUserStore from "@/store/modules/user";
    
    
    export const getState = () => {
      const { userInfo } = useUserStore();
      const state = {
        token: getToken(),
        accessUser: {
          loginName: userInfo.userName || "",
          realName: userInfo.userDisplayName || ""
        }
      };
      return state;
    };
    
    const { subApps } = getConfig(getState());
    
    export function registerApps() {
      try {
        registerMicroApps(subApps, {
          beforeLoad: [
            app => {
              console.log("before load", app);
            }
          ],
          beforeMount: [
            app => {
              console.log("before mount", app);
            }
          ],
          afterUnmount: [
            app => {
              console.log("before unmount", app);
            }
          ]
        });
      } catch (err) {
        console.log(err);
      }
    }
    
  • 新增容器,以及在路由表上增加对应路径的配置

    官方原话:当微应用信息注册完之后,一旦浏览器的url发生变化,便会自动触发qiankun的匹配逻辑,所有activeRule规则匹配上的微应用就会被插入到指定的container中,同时依次调用微应用暴露出的生命周期钩子。

    1. 新建subContainer组件,代码如下:
    
    
    
    <script setup>
    import { start } from "qiankun";
    import { registerApps } from "@/qiankun";
    
    onMounted(()=>{
       if (!window.qiankunStarted) {
         window.qiankunStarted = true;
         registerApps();
         start({
           prefetch: false, 
           
           
           
           
         });
       }
    })
    script>
    
    1. 路由表配置如下:
    
    export const routes = [
       
       {
           
           
           path: "/xxx/:pathMatch(.*)*",
           name: "xxxxx",
           meta: {},
           component: () => import("@/views/subContainer")
       },
    ]
    

微应用

  • vue3 + vite,路由模式为history

  • 新建qiankun相关配置文件

    1. 安装vite-plugin-qiankun插件(qiankun目前没有支持vite的文档)

    npm i vite-plugin-qiankun -D

    1. vite.config.js中配置插件
        
        import qiankun from "vite-plugin-qiankun";
    
        export default defineConfig() => {
            const { VITE_POWERED_BY_QIANKUN, VITE_PUBLIC_PATH } = env;
            return {
                base: VITE_PUBLIC_PATH,    
                plugins: [
                    
                    qiankun(VITE_POWERED_BY_QIANKUN, {
                      useDevMode: true
                    })
                ]
            }
        }
    
    1. 导出对应的生命周期钩子,以及初始化方式
       
       import { renderWithQiankun, qiankunWindow } from "vite-plugin-qiankun/dist/helper";
    
       export const render = (app, container) => {
         app.mount(container ? container.querySelector("#app") : "#app");
       };
       export const initQianKun = (app) => {
         renderWithQiankun({
           mount(props) {
             const { container } = props;
             render(app, container);
           },
           bootstrap() {
             console.log("bootstrap");
           },
           unmount() {
             app.unmount();
           }
         });
       };
       
       export const init = (app) => {
         qiankunWindow.__POWERED_BY_QIANKUN__ ? initQianKun(app) : render(app);
       };
    
    • 路由设置,如果是qiankun子应用的环境,增加对应的前缀
        
        import { createWebHistory, createRouter } from "vue-router";
        const VITE_POWERED_BY_QIANKUN = import.meta.env.VITE_POWERED_BY_QIANKUN;
        const router = createRouter({
        history: createWebHistory(
        qiankunWindow.__POWERED_BY_QIANKUN__
          ? `/xxx/${VITE_POWERED_BY_QIANKUN}/`
          : "/"
        ),
        routes: constantRoutes,
        scrollBehavior(to, from, savedPosition) {
        if (savedPosition) {
          return savedPosition;
        }
        return { top: 0 };
        }
        });
    
        export default router;
    
        
        import { createApp } from "vue";
        import { initQianKunApp } from "@/qiankun.js";
        import App from "./App";
        if (window.__POWERED_BY_QIANKUN__) {
          
          __webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
        }
        const app = createApp(App);
        initQianKunApp(app);
    
  • vue2 + webpack ,路由模式为 hash

    • 新建qiankun相关配置文件

      1. 配置webpack
           
          const { name } = require('./package');
          module.exports = {
            
            devServer: {
              headers: {
                'Access-Control-Allow-Origin': '*',
              },
            },
            configureWebpack: {
              output: {
                library: `${name}-[name]`,
                libraryTarget: 'umd', 
                jsonpFunction: `webpackJsonp_${name}`, 
              },
            },
          };
      
      1. 导出对应的生命周期钩子,以及初始化方式
          
          import App from './App'
          import router from './router'
          import store from './store'
          import { setToken, setAccessUser, } from "@/utils/auth";
      
          let instance = null
          export function render(props = {}) {
            const { container } = props
            instance = new Vue({
              router,
              store,
              render: h => h(App)
            }).$mount(container ? container.querySelector('#app') : '#app')
          }
      
          export async function bootstrap(props) {
            console.log('[vue] vue app bootstraped', props)
          }
          export async function mount(props, ...args) {
            console.log('[vue] props from main framework', props, args);
            setData(props)
            props.onGlobalStateChange((state, prev) => {
              
              console.log("🚀 ~ props.onGlobalStateChange ~ state:", state)
              setData(state)
            });
            render(props)
          }
          export async function unmount() {
            instance.$destroy()
            instance.$el.innerHTML = ''
            instance = null
          }
          
          function setData(state){
            if(state['token']){
              setToken(state.token)
            }
            if(state['accessUser']) {
              setAccessUser(state.accessUser)
            }
          }
      
          export default render
      
    • 路由配置

       
       import Router from 'vue-router'
       export const constantRouterMap = [ ... ]
       export default new Router({
         scrollBehavior: () => ({ y: 0 }),
         base: window.__POWERED_BY_QIANKUN__ ? '/xxx/report/' : '/',
         routes: constantRouterMap
       })
    
      import render from "./qiankun";
      
      export * from "./qiankun";
      if (window.__POWERED_BY_QIANKUN__) {
        __webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
      }else {
      
        render();
      }
    
  1. 部署上线需要注意资源路径的问题
  2. 不同服务器下的项目需要处理跨域问题
  3. qiankun还有手动加载微应用的方式,暂时还没有用到,可查看官方文档
阅读全文
下载说明:
1、本站所有资源均从互联网上收集整理而来,仅供学习交流之用,因此不包含技术服务请大家谅解!
2、本站不提供任何实质性的付费和支付资源,所有需要积分下载的资源均为网站运营赞助费用或者线下劳务费用!
3、本站所有资源仅用于学习及研究使用,您必须在下载后的24小时内删除所下载资源,切勿用于商业用途,否则由此引发的法律纠纷及连带责任本站和发布者概不承担!
4、本站站内提供的所有可下载资源,本站保证未做任何负面改动(不包含修复bug和完善功能等正面优化或二次开发),但本站不保证资源的准确性、安全性和完整性,用户下载后自行斟酌,我们以交流学习为目的,并不是所有的源码都100%无错或无bug!如有链接无法下载、失效或广告,请联系客服处理!
5、本站资源除标明原创外均来自网络整理,版权归原作者或本站特约原创作者所有,如侵犯到您的合法权益,请立即告知本站,本站将及时予与删除并致以最深的歉意!
6、如果您也有好的资源或教程,您可以投稿发布,成功分享后有站币奖励和额外收入!
7、如果您喜欢该资源,请支持官方正版资源,以得到更好的正版服务!
8、请您认真阅读上述内容,注册本站用户或下载本站资源即您同意上述内容!
原文链接:https://www.shuli.cc/?p=21210,转载请注明出处。
0

评论0

显示验证码
没有账号?注册  忘记密码?