props通信
registerMicroApps([
{
name: 'childApp',
entry: '//localhost:7100',
container: '#container',
activeRule: '/child',
props: {
// 传递静态数据
globalData: { version: '1.0' },
// 传递函数实现"子调父"
onEvent: (data) => console.log('收到子应用消息:', data)
}
}
]);
export async function mount(props) {
console.log(props.globalData);
props.onEvent({ type: 'FROM_CHILD' });
}
customEvent
const event = new CustomEvent('global-event', {
detail: { type: 'MSG', payload: '数据内容' }
});
window.dispatchEvent(event);
window.addEventListener('global-event', (e) => {
console.log('收到全局事件:', e.detail);
});
initGlobalState
import { initGlobalState } from 'qiankun';
const initialState = { user: { name: 'Admin' }, token: null };
const actions = initGlobalState(initialState);
actions.onGlobalStateChange((state, prevState) => {
console.log('全局状态变更:', prevState, '→', state);
});
export { actions };
export async function mount(props) {
props.onGlobalStateChange((state, prev) => {
console.log('子应用收到状态更新:', state);
});
props.setGlobalState({ token: 'NEW_TOKEN' });
}
localStorage
localStorage.setItem('SHARED_KEY', JSON.stringify(data));
window.addEventListener('storage', (e) => {
if (e.key === 'SHARED_KEY') {
console.log('存储数据变化:', JSON.parse(e.newValue));
}
});
postmessage
// 应用A
const channel = new BroadcastChannel('app-channel')
channel.postMessage({ type: 'MSG' })
// 应用B
const channel = new BroadcastChannel('app-channel')
channel.onmessage = (e) => console.log(e.data)