美文网首页
qiankun微服务系统,微应用中监听父级容器数据变化

qiankun微服务系统,微应用中监听父级容器数据变化

作者: callPromise | 来源:发表于2021-06-18 16:12 被阅读0次

initGlobalState(state)

参数

state - Record<string, any> - 必选

用法
定义全局状态,并返回通信方法,建议在主应用使用,微应用通过 props 获取通信方法。

返回

MicroAppStateActions

onGlobalStateChange: (callback: OnGlobalStateChangeCallback, fireImmediately?: boolean) => void, 在当前应用监听全局状态,有变更触发 callback,fireImmediately = true 立即触发 callback

setGlobalState: (state: Record<string, any>) => boolean, 按一级属性设置全局状态,微应用中只能修改已存在的一级属性

offGlobalStateChange: () => boolean,移除当前应用的状态监听,微应用 umount 时会默认调用

示例:

主应用中entry类文件,例如Vue的main.js
import { registerMicroApps, runAfterFirstMounted, start, initGlobalState } from 'shsc-qiankun'

const globalActions = initGlobalState({ isLogout: false })
Vue.prototype.$globalActions = globalActions
主应用中使用
 // 容器退出登录,给微应用传递状态,在微应用中进行监听、缓存处理等
this.$globalActions.setGlobalState({ isLogout: true })
微应用中监听,在main.js中注册父级传来的onGlobalStateChange
export async function mount (props = {}) {
  const { render } = props
  // console.log('[vue] app mount')
  router = new VueRouter({ mode: 'history', routes })
  // 设置通讯
  Vue.prototype.$onGlobalStateChange = props.onGlobalStateChange
  Vue.prototype.$setGlobalState = props.setGlobalState

  instance = render(instance, Vue, App, { router, store, i18n, scui, gaiaStore })
}
例如在App.vue中使用
mounted () {
    this.$onGlobalStateChange((state, prev) => {
      if (state.isLogout) {
        // 清除缓存
        this.clearStrutsTree()
      }
    })
}

相关文章

网友评论

      本文标题:qiankun微服务系统,微应用中监听父级容器数据变化

      本文链接:https://www.haomeiwen.com/subject/upzkyltx.html