3. 实践基于qiankun的微前端demo - 子应用

2020-05-19  本文已影响0人  木头就是我呀

🤖 创建子应用one

yarn add vue-router
import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'

import routes from "./router";
import './public-path'

Vue.use(VueRouter)

Vue.config.productionTip = false

let router = null
let instance = null

function render() {
  router = new VueRouter({
    base: window.__POWERED_BY_QIANKUN__ ? 'one' : '/',
    mode: 'history',
    routes
  })

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

// 生命周期 - 挂载前
export async function bootstrap(props) {
  console.log('one bootstrap');
}
// 生命周期 - 挂载后
export async function mount() {
  console.log('one mount');
  // 渲染
  render()
}
// 生命周期 - 解除挂载
export async function unmount(){
  console.log('one unmount');
}

// 本地调试
if(!window.__POWERED_BY_QIANKUN__){
  render()
}
import Home from './../components/Home'
import About from './../components/About'


const routes = [
    {
        path: '/',
        name: 'home',
        component: Home,
    },
    {
        path: '/about',
        name: 'about',
        component: About,
    }
]

// 注意 不是导出router对象
export default routes
<template>
    <div class="about">
        this is one about
    </div>
</template>

<script>
    export default {
        name: "About"
    }
</script>

<style scoped></style>
<template>
    <div class="home">
        this is one home
    </div>
</template>

<script>
    export default {
        name: "Home"
    }
</script>

<style scoped></style>
if(window.__POWERED_BY_QIANKUN__){
    __webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__
}
const {name} = require('./package')

const port = 6661

module.exports = {
    devServer: {
        port,
        // 允许被主应用跨域fetch请求到
        headers: {
            'Access-Control-Allow-Origin':'*'
        }
    },
    configureWebpack: {
        output: {
            library: `${name}-[name]`,
            // 把子应用打包成umd库格式
            libraryTarget: 'umd',
            jsonpFunction: `webpackJsonp_${name}`
        }
    }
}
<template>
  <div id="app">
    <router-link to="/">首页</router-link>
    <router-link to="/about">about</router-link>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'App',
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

可以看到,页面上出现了我们的one应用的App.vue页面,和单独运行one是一样的效果,并且右边的控制台也在对应的生命钩子中打印出对应的信息,此时,one应用就成功的装载到了main里面。

此时,两个微前端子项目就成功的集成到主项目main中,并且其对应的生命钩子也成功的触发。
接下来会介绍主子任务如何通讯,qiankun框架也很清楚的在文档里展现出来了,我们实践一下。
4. 实践基于qiankun的微前端demo - 主应用下发参数

上一篇 下一篇

猜你喜欢

热点阅读