vue中使用微前端qiankun


什么是微前端

微前端是一种多个团队通过独立发布功能的方式来共同构建现代化 web 应用的技术手段及方法策略。

介绍

qiankun 是一个基于 single-spa 的微前端实现库,旨在帮助大家能更简单、无痛的构建一个生产可用微前端架构系统。

qiankun 孵化自蚂蚁金融科技基于微前端架构的云产品统一接入平台,在经过一批线上应用的充分检验及打磨后,我们将其微前端内核抽取出来并开源,希望能同时帮助社区有类似需求的系统更方便的构建自己的微前端系统,同时也希望通过社区的帮助将 qiankun 打磨的更加成熟完善

 

具体描述可查看 文档 和 Github

 

一、配置主应用

1、使用vue cli快速创建应用

2、安装qiankun

npm i qiankun -S

3、主应用main.js修改如下

import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";

Vue.config.productionTip = false;

/**
 * 中央事件总线EventBus,用于通信。
 * 在Vue中可以使用 EventBus 来作为沟通桥梁的概念,就像是所有组件共用相同的事件中心,可以向该中心注册发送事件或接收事件
 */
Vue.prototype.$EventBus = new Vue()

import {registerMicroApps,runAfterFirstMounted, setDefaultMountApp, start} from 'qiankun';
import fetch from 'isomorphic-fetch';
let app = null;

let count1 = 0;
let count = 0;
function render({ appContent, loading }) {
  /*examples for vue*/
  if (!app) {
    app = new Vue({
      el: '#app',
      router,
      store,
      data() {
        return {
          content: appContent,
          loading,
        };
      },
      render(h) {
        return h(App, {
          props: {
            content: this.content,
            loading: this.loading,
          },
        });
      },
    });
  } else{
    app.content = appContent;
    app.loading = loading;
  }
}

function genActiveRule(routerPrefix) {
  return location => location.pathname.startsWith(routerPrefix);
}

render({ loading: true });


const request = url =>
  fetch(url, {
    referrerPolicy: 'origin-when-cross-origin',
  });


//注册子应用
registerMicroApps([
    {
      name: 'child1',
      entry: '//localhost:7100',
      render,//普通模式
      activeRule: genActiveRule('/child1')
    },
  ],
  {
    beforeLoad: [
      app => {
        console.log('before load', app);
      },
    ],
    beforeMount: [
      app => {
        console.log('before mount', app);
      },
    ],
    afterMount: [
      app => {
        console.log('after mount', app);
      },
    ],
    afterUnmount: [
      app => {
        console.log('after unload', app);
        app.render({appContent: '', loading: false});
      },
    ],
  },
  {
    fetch: request,
  },
);

/**
 * @description 设置哪个子应用程序在主加载后默认处于活动状态
 * @param defaultAppLink: string 跳转链接
 */
setDefaultMountApp('/about');

/**
 * @description 第一个应用构建完成后执行
 * @param 要执行的函数
 */
runAfterFirstMounted(() => console.info('first app mounted'));

/**
 * @description 启动主应用
 * @param prefetch 是否在第一次安装子应用程序后预取子应用程序的资产,默认为 true
 * @param jsSandbox 是否启用沙盒,当沙盒启用时,我们可以保证子应用程序是相互隔离的,默认为 true
 * @param singular 是否在一个运行时只显示一个子应用程序,这意味着子应用程序将等待挂载,直到卸载之前,默认为 true
 * @param fetch 设置一个fetch function,默认为 window.fetch
 */
start({ prefetch: true, fetch: request });

  

4、修改App.vue 

<template>
<!-- 这里id不能使用默认app,子程序会直接挂在这个节点上,会直接调整到子程序 --> <div id="appmain"> <div id="nav"> <a href="javascript:;" @click="goto('测试','/child1/about1')">Home</a> | <router-link to="/about">About</router-link> </div> <router-view v-if="!ischildApp"/> <div v-html="content" v-show="ischildApp"></div> </div> </template> <script> export default { props: { content: String, }, computed:{ ischildApp:function(){ if(this.$route.path.match('child1')){ return true; }else{ return false; } }, }, methods:{ goto(title, href) { console.log("title",title,"href",href) window.history.pushState({}, title, href); // this.$router.push(op.key) }, } } </script> <style> #appmain { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; } #nav { padding: 30px; } #nav a { font-weight: bold; color: #2c3e50; } #nav a.router-link-exact-active { color: #42b983; } </style>

  

二、配置子应用

1、使用vue cli快速创建应用

2、子应用无需安装qiankun

3、主应用main.js修改如下

import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";

Vue.config.productionTip = false;


let instance = null;
 
function render(props = {}) {
  const { container } = props; 
  instance = new Vue({
    router,
    store,
    render: h => h(App),
  }).$mount('#app');
}

if (!window.__POWERED_BY_QIANKUN__) {
  	render();
}else {
	__webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
}
 
 
export async function bootstrap() {
    console.log('vue app bootstraped');
}

export async function mount(props) {
    console.log('props from main app', props);
    render();
}

export async function unmount() {
    instance.$destroy();
    instance = null;
    router = null;
}

  

4、vue.config.js修改如下

const path = require('path');
const { name } = require('./package');

function resolve(dir) {
    return path.join(__dirname, dir);
}


const port = 7100
module.exports = {
	lintOnSave: false,
	devServer: {
	    // host: '0.0.0.0',
	    hot: true,
	    disableHostCheck: true,
	    port,
	    overlay: {
	      warnings: false,
	      errors: true
	    },
	    headers: {
	      'Access-Control-Allow-Origin': '*',
	    }
	},
	// 自定义webpack配置
    configureWebpack: {
        resolve: {
            alias: {
                '@': resolve('src'),
            },
        },
        output: {
            // 把子应用打包成 umd 库格式
            library: `${name}-[name]`,
            libraryTarget: 'umd',
            jsonpFunction: `webpackJsonp_${name}`,
        },
    },
}

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM