マイクロフロントエンドのシングルスパアプリケーションデモ

1.サブアプリケーションの変更
1.main.jsファイル

import Vue from 'vue'
import singleSpaVue from 'single-spa-vue';
import router from './router';
import App from './App.vue'

Vue.config.productionTip = false

const appOptions = {
    
    
  el: '#vue', // 主应用中你需要挂载到的地方 的div, id名
  router,
  render: h => h(App)
}
// 如果是在主应用中访问
if(window.singleSpaNavigate){
    
    
  __webpack_public_path__ = 'http://localhost:10000/'
}

// 单独访问子应用的正常挂载
if(!window.singleSpaNavigate){
    
    
  delete appOptions.el;
  new Vue(appOptions).$mount('#app');
}
// single-spa 的 生命周期
const vueLifeCycle = singleSpaVue({
    
    
  Vue,
  appOptions
});
// 子应用必须导出 以下生命周期 bootstrap、mount、unmount
export const bootstrap = vueLifeCycle.bootstrap;
export const mount = vueLifeCycle.mount;
export const unmount = vueLifeCycle.unmount;

// 需要打包成一个lib 去给 父应用使用 --- 去创建组件 vue.config.js
export default vueLifeCycle;

2、vue.config.js

module.exports = {
    
    
  configureWebpack: {
    
    
      output: {
    
    
          library: 'singleVue', // 随意起的名字
          libraryTarget: 'umd'  // 打包完是umd模块
      },
      devServer:{
    
    
          port:10000
      }
  }
}

2.メインアプリケーション
1.App.vueに
divid = "vue" //サブアプリケーションのマウントに対応する必要があります

<div id="nav">
    <router-link to="/sub">去子应用项目</router-link> 
    <div id="vue"></div>  // id与子应用中的挂载 相对应
</div>

2、main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router';
import {
    
     registerApplication, start } from 'single-spa';

Vue.config.productionTip = false

// 通过script url 无跨域 加载进来。
const loadScript = async (url)=> {
    
    
  await new Promise((resolve,reject)=>{
    
    
    const script = document.createElement('script');
    script.src = url;
    script.onload = resolve;
    script.onerror = reject;
    document.head.appendChild(script);
  });
}
registerApplication(
  'singleVue', // 起的名字,随便起
  async ()=>{
    
     // 必须是promise函数
    // 顺序有要求 
    await loadScript('http://localhost:10000/js/chunk-vendors.js');
    await loadScript('http://localhost:10000/js/app.js');
    return window.singleVue
  },
  location => location.pathname.startsWith('/sub') // 自定义的路由名字
)
start();

new Vue({
    
    
  router,
  render: h => h(App),
}).$mount('#app')

// 这个地方要注意 ,如果你的router 不是 history模式,匹配的时候是 ‘#/sub’
 location => location.pathname.startsWith('/sub') 

これは基本的に達成できます。しかし、スタイルは分離されていません、それはお互いに影響を及ぼします、私は後でそれを追加し続けます

おすすめ

転載: blog.csdn.net/Beth__hui/article/details/112802480