在vue项目上使用阿里qiankun ——项目通讯篇(二)

通讯方式主要运用的qiankun提供的通讯api initGlobalState 以及vuex动态添加模块的方法
registerModule

1、在qiankun文件夹下创建share.js
/*
 * @Author: Hzh
 * @Date: 2021-05-07 16:02:48
 * @LastEditTime: 2021-07-22 14:52:57
 * @LastEditors: Hzh
 * @Description:
 */
import Vue from 'vue'
import store from '../store'
import {
    initGlobalState } from 'qiankun'

const initialState = Vue.observable({
   
  userInfo: {
   }, // 当前登录用户信息
  globalConfig: {
   },
  sources: [], // 所有资源
  btnCodeList: [] // 按钮权限

})

// 初始化state
export const actions = initGlobalState(initialState)

actions.onGlobalStateChange((newValue) => {
   
  // console.log('newValue', newValue)
  // 修改全局下发的数据
  for (const key in newValue) {
   
    initialState[key] = newValue[key]
    // if (key === 'userInfo') {
   
    //   store.commit('UPDATE_USER_INFO', newValue[key])
    //   continue
    // }
    // if (key === 'globalConfig') {
   
    //   store.commit('UPDATE_GLOBAL_CONFIG', newValue[key])
    //   continue
    // }
    if (key === 'sources') {
   
      store.commit('qiankun/UPDATE_GLOBAL_SOURCE', newValue[key])
      continue
    }
  }
})

//  按一级属性设置全局状态,微应用中只能修改已存在的一级属性
// actions.setGlobalState(state);

// 自定义一个资源去重的方法
actions.distinctSource = (sources, addData) => {
   
  const newData = []
  for (let i = 0; i < addData.length; i++) {
   
    let flag = true
    for (let j = 0; j < sources.length; j++) {
   
      if (sources[j].code === addData[i].code) {
   
        flag = false
        break
      }
    }
    if (flag) {
   
      newData.push(addData[i])
    }
  }
  sources = sources.concat(newData)
  return sources
}

// 自定义一个获取state的方法下发到子应用
actions.getGlobalState = (key) => {
   
  // 有key,表示取globalState下的某个子级对象
  // 无key,表示取全部
  return key ? initialState[key] : initialState
}

// 将action对象绑到Vue原型上,为了项目中其他地方使用方便
Vue.prototype.$actions = actions
// 传入子应用的公共数据
export const share = {
   
  getGlobalState: actions.getGlobalState, 
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值