前端微服务qiankun使用基础及应用传参

一,主应用入口文件

import Vue from 'vue'
import app from './App.vue'
import router from './router/index.js'
//引入状态管理机
import actions from './action.js'
//引入乾坤中需要的模块  注册应用,设置默认应用
import { registerMicroApps, start, setDefaultMountApp } from 'qiankun'

//注册应用
registerMicroApps([
      {
        name: 'vueapp',
        entry: '//localhost:8081', // 子应用入口
        container: '#vue',//渲染子应用容器
        activeRule: '/vue3',//主应用路由适配path 当url地址为 https://xxxxxxx.com/vue3/..........时,进入  //localhost:8081/vue3
        props: { age: '37', actions } //传参及状态管理机给子应用
      },
      {
        name: 'vueapp2',
        entry: '//localhost:8082', // 子应用入口
        container: '#vue',
        activeRule: '/vue4',
        props: { age: '37', actions }
      }
    ],
      {
        beforeLoad: (app) => {
          console.log(app.name, '加载前调用')
        },
        beforeMount: [(app) => {
          console.log('渲染前调用')
        }]
      }
)
//启动乾坤
start({
  scanbox: { strictStylelsolation: true } // 启动样式隔离
})
//设置默认子应用
setDefaultMountApp('/vue4')

new Vue({
  router,//加然router中可能不做任何path配置,但也要注册路由实例
  render: h => (app)
}).$mount('#app-base')

二,主应用状态管理机

import { initGlobalState } from 'qiankun'
const state = {}
const actions = initGlobalState
//监听state变化
actions.onGlobalStateChange((state, prev) => {
  //state变更后的状态,prev变更前的状态
  console.log('父应用检测到变化')
})
export default actions

三,子应用入口文件

/*eslint-disable*/
if (window.__POWERED_BY_QIANKUN__) {
  __webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
}
/*eslint-enable*/
import Vue from 'vue';
import VueRouter from 'vue-router';
import App from './App.vue';
import routes from './router';
import store from './store';

Vue.config.productionTip = false;

let router = null;
let instance = null;
function render(props = {}) {
  const { container } = props;
  router = new VueRouter({
    base: window.__POWERED_BY_QIANKUN__ ? '/app-vue/' : '/',
    mode: 'history',
    routes,
  });

  instance = new Vue({
    router,
    store,
    render: (h) => h(App),
  }).$mount(container ? container.querySelector('#app') : '#app');
}

// 独立运行时
if (!window.__POWERED_BY_QIANKUN__) {
  render();
}
//只有项目在第一次加载时才会被调用
export async function bootstrap() {
  console.log('[vue] vue app bootstraped');
}
//项目加载前都会被计用
export async function mount(props) {
    /*
    挂载全局,在组件中可使用this.$actions.setGlobalState(state)修改状态,
    触发子应用及主应用的监听
    */
  Vue.prototype.$actions = props.actions   
  props.onGlobalStateChange((state, prev) => {
    //state变更后的状态,prev变更前的状态  使用 actions.setGlobalState(state);改变状态,触发状态管理机的监听
    console.log('父应用检测到变化')
  })
  console.log('[vue] props from main framework', props);
  render(props);
}
//应用在销毁时调用
export async function unmount() {
  instance.$destroy();
  instance.$el.innerHTML = '';
  instance = null;
  router = null;
}

你可能感兴趣的:(微服务,前端)