快速上手微前端框架 icestark (二)

Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情

快速上手微前端框架 icestark (一)

思考

微前端中都需要哪些通信

  • 主应用与子应用通信
  • 子应用之间的通信

主应用与子应用通信

主应用传参到子应用

store

使用 @ice/stark-data 包,需要单独安装

npm install @ice/stark-data --save
复制代码

在主应用中设置全局用户信息,主应用中更新数据

import { store } from '@ice/stark-data'
console.log(store)
const userInfo = { name: 'Sabo', age: 29 }
store.set('user', userInfo)

store.set('language', 'CH') // 设置全局语言

setTimeout(() => {
  store.set('language', 'EN');
}, 3000);
复制代码

子应用中获取用户信息,监听主应用数据变化

import { store } from '@ice/stark-data'
const userInfo = store.get('user')
console.log('userInfo: ', userInfo)

// 监听变化
store.on('language', (lang) => {
  console.log(`current language is ${lang}`)
}, true)
复制代码
event

主应用监听子应用数据变化,接收子应用发送的数据

主应用设置监听事件

import { event } from '@ice/stark-data'
event.on('freshMessage', (res: string) => {
  console.log('App ', res)
})
复制代码

子应用触发事件

import { event } from '@ice/stark-data'
setTimeout(() => {
  event.emit('freshMessage', 'vue message')
}, 1000)
复制代码

子应用主应用之间互相跳转

appHistory

子应用跳转主应用 about 页, 跳转子应用 react

注意 在本地添加完对应的代码后需要重新刷新页面,否则路由跳转会出现页面白屏的情况

import appHistory from '@ice/stark-app/lib/appHistory'
appHistory.push('/about')
appHistory.push('/react')
复制代码

使用JS原生功能实现通信

对于主应用和微应用,运行时都共享了当前页面的 location、Cookie、LocalStorage、window 等全局信息,因此应用间的通信,也可以通过这些方案实现

本地页面功能演示

总结

到目前为止,icestark 的微前端框架的基本能力都已经上手了,在实际业务开发中,还需要基于业务需求进行相应的优化调整

GitHub 案例代码

github.com/gywgithub/i…

猜你喜欢

转载自juejin.im/post/7078968025088524302