关于微前端--乾坤(qiankun)如何把主应用的参数传给子应用

594 阅读1分钟

一、主应用新建一个actions.js文件

利用initGlobalState方法来定义全局变量(其属于qiankun的全局状态储存机制)并调用setGlobalState来存储需要传出的数据,子应用中使用onGlobalStateChange来接收

//actions.js 具体代码如下
import { initGlobalState } from 'qiankun'
const initialState = {}
const actions = initGlobalState(initialState)
export default actions

二、主应用配置需要传出的数据(调用setGlobalState)

下图是我从主应用中传出子应用的menuId及子应用的路由

在这里插入图片描述

三、子应用在mount生命周期中使用onGlobalStateChange来接收参数

export async function mount(props) {
  console.log('应用每次进入都会调用 mount 方法,通常我们在这里触发应用的渲染方法', props)
  props.onGlobalStateChange((state) => {
    console.log('子应用接收的参数', state)
    console.log('子应用接收参数--menuId', state.menuId)
    console.log('子应用接收参数--路由', JSON.parse(state.childrenRouter))
    if (state.menuId) {
      store.commit('SET_MENU_ID', state.menuId)
    }
  }, true)
  render(props)
}

在这里插入图片描述

四、注意点

主应用点击进入子应用必须使用window.history.pushState({}, '', route.path);不能使用window.location.href不然参数传不了

五、 相关文章

基于ElementUi&Antd再次封装基础组件文档


vue3+ts基于Element-plus再次封装基础组件文档


vite+vue3+ts项目搭建之集成qiankun