vue3.0+乾坤實現微應用


首先是引入乾坤

npm i qiankun -S

在main.js中,引入乾坤

import { registerMicroApps,runAfterFirstMounted,addGlobalUncaughtErrorHandler } from 'qiankun';

注冊

registerMicroApps( {
      name: 'son',
      entry: 'http://localhost:8001/',
      container: '#sonList', // 微應用掛載節點 - 微應用加載完成后將掛載在該節點上
      activeRule:'son',
      // activeRule: getActiveRule('son'),
      // props: {
      //   msg: {
      //     data: {
      //       mt: 'hello,我是來自父親的關懷!'
      //     }
      //   },
      //   fn: {
      //     show(msg) {
      //       console.log('one:', msg)
      //     }
      //   }
      //   // routerBase: '/sub-vue' // 下發路由給子應用,子應用根據該值去定義qiankun環境下的路由
      // }
    }, {
  beforeLoad: app => {
    console.log('before load app.name====>>>>>', app.name)
    return Promise.resolve();
  },
  beforeMount: [
    app => {
      console.log("dddddd");
      console.log('[LifeCycle] before mount %c%s', 'color: green;', app.name);
    },
  ],
  afterMount: [
    app => {
      console.log('[LifeCycle] after mount %c%s', 'color: green;', app.name);
      return Promise.resolve();
    }
  ],
  afterUnmount: [
    app => {
      console.log('[LifeCycle] after unmount %c%s', 'color: green;', app.name);
    },
  ],
})

判斷是否調用成功和異常處理

runAfterFirstMounted(() => {
  console.log('第一個子應用加載完畢后的回調')
})
/**
 * 添加全局的未捕獲異常處理器
 */
 addGlobalUncaughtErrorHandler((event) => {
  const { message: msg } = event;
  // 加載失敗時提示
  if (msg && msg.includes("died in status LOADING_SOURCE_CODE")) {
   console.log("微應用加載失敗,請檢查應用是否可運行___"+msg);
  }
});
runAfterFirstMounted(() => {
  console.log('第一個子應用加載完畢后的回調')
})
/**
 * 添加全局的未捕獲異常處理器
 */
 addGlobalUncaughtErrorHandler((event) => {
  const { message: msg } = event;
  // 加載失敗時提示
  if (msg && msg.includes("died in status LOADING_SOURCE_CODE")) {
   console.log("微應用加載失敗,請檢查應用是否可運行___"+msg);
  }
});

然后在顯示的vue中,在哪里使用就在哪里打開,當然,也可以放到main.js全局開啟乾坤

<template>
  <div id="sonLit"></div>
</template>

<script >
import { onMounted } from 'vue'
import { start } from "qiankun";
export default {
  setup() {
    onMounted(() => {
      if (!window.qiankunStarted) {
        window.qiankunStarted = true;
        start({
            prefetch: true, // 開啟預加載
          sandbox: {
            strictStyleIsolation: true,
            experimentalStyleIsolation: true,
          },
        });
      }
    });
  },
};
</script>

在子應用中,添加public-path.js

/* eslint-disable */
if (window.__POWERED_BY_QIANKUN__) {
    __webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__
  }
  /* eslint-disable */

然后引入 import './public-path'

修改router,直接export default routes,將注冊放到main.js中

import { createRouter, createWebHistory } from 'vue-router';
let router = null;
let instance = null;
let history = null;
 function render(props = {}) {
    const { container } = props;
    console.log("props.name",props.name);
    history = createWebHistory(window.__POWERED_BY_QIANKUN__ ? `${props.name}` : '/');
    router = createRouter({
      history,
      routes,
    });
 instance = createApp(App);
    instance.use(router);
    instance.use(store);
instance.mount(container ? container.querySelector('#app') : '#app');
  }

// 本地調試
  if (!window.__POWERED_BY_QIANKUN__) {
    render()
  }


  // 生命周期 - 掛載前,在這里由主應用傳過來的參數
export async function bootstrap() {
 
      // console.log('one bootstrap'+JSON.stringify(props))
    console.log( localStorage.getItem('test'));
    
  }
  
  // 生命周期 - 掛載后
  export async function mount(props) {
   
    render(props)

      //console.log(props.msg.data);
      
    // // 主應用傳遞過來的 props.fn 是一個對象。循環遍歷下,將各個屬性綁定到子應用的原型鏈上
    // Object.keys(props.fn).forEach(method => {
    //     createApp.prototype[`$${method}`] = props.fn[method]
    // })
    // 渲染
  
  }
  
  // 生命周期 - 解除掛載
  export async function unmount() {
    instance.unmount();
    instance._container.innerHTML = '';
    instance = null;
    router = null;
    history.destroy();
    // instance=instance.unmount(props);
    // instance._container.innerHTML = "";
    // instance = null;
    // router = null
  }

在vue.config.js中

const { name } = require('./package.json')
const port = 8001

module.exports = {
  devServer: {
    port,
    // 允許被主應用跨域fetch請求到
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Authorization': '0b72a02adf334844a0367e021ad1c25c'
    }, proxy: {
      '/omg': {
        target: 'http://127.0.0.1',
        changeOrigin: true,
        ws: true,
        pathRewrite: { '^/omg': '' }
      }
    }
  },
  configureWebpack: {
    output: {
      library: `${name}-[name]`,
      // 把子應用打包成umd庫格式
      // 當我們把 libraryTarget 設置為 umd 后,我們的 library 就暴露為所有的模塊定義下都可運行的方式了,主應用就可以獲取到微應用的生命周期鈎子函數了
      libraryTarget: 'umd',
      jsonpFunction: `webpackJsonp_${name}`
    }
  }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM