当前位置:网站首页>Three ways to realize application communication in Qiankun (props, initglobalstate, socket.io)
Three ways to realize application communication in Qiankun (props, initglobalstate, socket.io)
2022-06-10 02:47:00 【Lyrelion】
Catalog
1.1 Defined in the main application props
1.2 Get from micro application props
2.1.3 return ( return MicroAppStateActions example )
2.2 initGlobalState(state) Communication principle
3.1.1 register MicroAppStateActions example
3.1.2 Use MicroAppStateActions example
3.2.1 stay main.ts Receive parameters in
3.2.2 In actual business related .vue Parameters used in the file
5. Comparison of communication modes
5.2 Use qiankun Provided API initGlobalState communicate
5.3 Use external plug-ins socket.io communicate
1. props
1.1 Defined in the main application props
In the main application , When registering the basic configuration information of the micro application , Definition props , Write the information that needs to be passed to the micro application
As shown in the following code ,props Parameters passed to micro applications are added in
window.microApp = [
{
name: 'micro-app', // The only value . Recommendations and package.json Medium name Agreement
entries: {
dev: '//localhost:8081/', // development environment
product: '//xxx.xxx.x.xxx:8104/vue3-backstage-micro-app/', // on-line
},
container: '#micro-app', // Containers ID
activeRule: getActiveRule('#/vue'), // Activation path
props: {
id: 'props Value transfer mode '
},
},
];
1.2 Get from micro application props
Micro applications in qiankun Framework of the mount In the life cycle , Can get props
Because in mount In the life cycle , Called render() function , So in render To define the receiving props Parameters of
function render(props?: any) {
console.log(props?.id);
}
...
// Life cycle
....
export async function mount(props): Promise<void> {
render(props);
}
...Print the results :

2. initGlobalState(state)
2.1 Basic instructions
initGlobalState() yes qiankun Communications provided API
API explain - qiankun
https://qiankun.umijs.org/zh/api#initglobalstatestate
2.1.1 Parameters
state - Record<string, any> - Mandatory
2.1.2 usage
Define the global state , And return the communication method , It is recommended to use in the main application , Micro application through props Get the communication method
2.1.3 return ( return MicroAppStateActions example )
Monitor the global state in the current application , There is a change trigger callback,fireImmediately = true Immediately triggered callback
onGlobalStateChange:
(callback: OnGlobalStateChangeCallback, fireImmediately?: boolean) => void
Set global state by one level property , In micro application, you can only modify the existing first level attributes
setGlobalState:
(state: Record<string, any>) => boolean
Remove the status monitor of the current application , Microapplication umount Call by default
offGlobalStateChange:
() => boolean
2.1.4 The official sample
Main application :
import { initGlobalState, MicroAppStateActions } from 'qiankun';
// initialization state
const actions: MicroAppStateActions = initGlobalState(state);
actions.onGlobalStateChange((state, prev) => {
// state: The changed state ; prev The state before the change
console.log(state, prev);
});
actions.setGlobalState(state);
actions.offGlobalStateChange();Microapplication :
// From life cycle mount Get the communication method in , Usage and master Agreement
export function mount(props) {
props.onGlobalStateChange((state, prev) => {
// state: The changed state ; prev The state before the change
console.log(state, prev);
});
props.setGlobalState(state);
}2.2 initGlobalState(state) Communication principle
qiankun The interior provides initGlobalState Method , Used for registration MicroAppStateActions example
MicroAppStateActions The example contains three methods for application communication :
- onGlobalStateChange: register The observer function - Respond to globalState change , stay globalState Trigger when a change occurs The observer function .
- setGlobalState: Set up globalState - When setting a new value , It will be carried out internally Shallow examination , If you find globalState A notification is triggered when a change occurs , Notice to all The observer function 【 Deep listening 】
- offGlobalStateChange: Cancel The observer function - The instance no longer responds globalState change

in summary :
- Every app can register The observer Into the observer pool
- Each application can be modified globalState, Trigger all The observer function , Realize application communication
3. actual combat
scene : After the main application logs in , You need to pass the information obtained after login to each micro application token
3.1 Main application
3.1.1 register MicroAppStateActions example
import {
registerMicroApps,
start,
initGlobalState
MicroAppStateActions,
} from 'qiankun';
....
// Register micro application communication example
const initialState = {};
const actions: MicroAppStateActions = initGlobalState(initialState);
export {
start, // export qiankun Start function of
actions, // Export communication examples
}
3.1.2 Use MicroAppStateActions example
On the login page , Use 3.1.1 Defined MicroAppStateActions example :
- register The observer function :actions.onGlobalStateChange((state, prevState) => { ... })
- Trigger The observer function :actions.setGlobalState({ ... })【 Deep listening 】
<template>
<button @click="handleLogin"> Sign in </button>
</template>
<script lang="ts">
import { defineComponent, onMounted } from 'vue';
import { actions } from '@/hooks/micro-app';
export default defineComponent({
name: 'Login',
setup() {
onMounted(() => {
/**
* Register an observer function
* @param state The changed state
* @param prevState: The state before the change
*/
actions.onGlobalStateChange((state, prevState) => {
console.log(" The main application observer :token The value before the change is ", prevState.token);
console.log(" The main application observer :token The changed value is ", state.token);
});
});
/**
* Click login
*/
const handleLogin = () => {
// After successful login , Set up token
actions.setGlobalState({ token: new Date() });
...
};
return {
handleLogin,
};
}
})
</script>
3.2 Microapplication
stay 3.1 in , Obtained in the main application token It has been recorded in globalState in , The next step is to get it in the micro application
3.2.1 stay main.ts Receive parameters in
function render(props?: any) {
if (props) {
/**
* Register an observer function
* @param state The changed state
* @param prevState: The state before the change
*/
props.onGlobalStateChange(
(state: { token: any }, prevState: { token: any }) => {
// state: The changed state ; prevState: The state before the change
console.log(" Micro application observer :token The value before the change is ", prevState.token);
console.log(" Micro application observer :token The changed value is ", state.token);
}
);
}
}
// Life cycle
export async function mount(props): Promise<void> {
render(props);
}
3.2.2 In actual business related .vue Parameters used in the file
First step : newly build /hooks/actions.ts, Store instance methods for global usage communication
function emptyAction(...args: any[]) {
// Warning : Prompt that you are currently using empty Action
console.warn("Current execute action is empty!");
}
class Actions {
// The default value is empty Action
actions = {
onGlobalStateChange: emptyAction,
setGlobalState: emptyAction,
};
/**
* Set up actions
*/
setActions(actions: {
onGlobalStateChange: () => void;
setGlobalState: () => void;
}) {
this.actions = actions;
}
/**
* mapping
*/
onGlobalStateChange(...args: any[]) {
return this.actions.onGlobalStateChange(...args);
}
/**
* mapping
*/
setGlobalState(...args: any[]) {
return this.actions.setGlobalState(...args);
}
}
const actions = new Actions();
export default actions;
The second step : Import... In the entry file /hooks/actions.ts , And inject reality into it Actions
function render(props?:any) {
if (props) {
// Inject actions example
actions.setActions(props);
}
...
}
// Life cycle
export async function mount(props): Promise<void> {
render(props);
}The third step : When communication parameters are required vue In the page , introduce /hooks/actions.ts, And monitor
<script lang="ts">
import { defineComponent, onMounted } from "vue";
import actions from "@/hooks/actions"; // introduce
export default defineComponent({
setup() {
onMounted(() => {
/**
* Register an observer function
* @param state The changed state
* @param prevState: The state before the change
*/
actions.onGlobalStateChange(
(state: { token: any }, prevState: { token: any }) => {
console.log(" Micro application observer :token The value before the change is ", prevState.token);
console.log(
" Micro application observer :token The changed value is ",
state.token
);
}
);
});
},
});
</script>
Print the results :

Explain the following :
Before the main application logs in :token = undefined
After the main application logs in :token = Time 111
Before micro application loading :token = undefined
After the micro application is loaded :token = Time 111( Passed by the main application )
Changes have taken place in micro applications token after , Both the main application and the micro application trigger the number of observers actions.onGlobalStateChange;
Before change , In the main application micro application token = Time 111;
After change , In the main application micro application token = Time 222;
4. socket.io
No examples yet
5. Comparison of communication modes
5.1 Use props communicate
advantage :
- Easy to use
- fit initial load Micro applications deliver messages
shortcoming :
- Micro application independent runtime , Can't use
- Micro applications need to understand the contents of the state pool first , And then communicate
- After the micro application is mounted , Cannot monitor in real time
5.2 Use qiankun Provided API initGlobalState communicate
advantage :
- Easy to use , High official support
- fit Less communication Business scenario of
- It can realize real-time monitoring
shortcoming :
- Micro application independent runtime , Can't use
- Micro applications need to understand the contents of the state pool first , And then communicate
5.3 Use external plug-ins socket.io communicate
advantage :
- Micro applications are not affected by the primary application , Can run independently
- Unlimited usage scenarios
- It can realize real-time monitoring
shortcoming :
- You need to write the server code
- It won't be used , The cost of learning
边栏推荐
- How to use Google home speaker voice to control zhiting home cloud devices?
- (W10) prtsc screenshot key cannot be used normally - solution
- Double pointer | 27 Removing Elements
- The local storage database SQLite of the uni app mobile terminal has no storage restrictions
- MySQL 8.0.28 installation and configuration method graphic tutorial (compressed package method)
- mysql 8.0.29 winx64. Graphic tutorial of zip installation and configuration method
- Tips for college students' life: using tempermonkey to learn online lessons | check questions
- Add receiving address [project mall]
- Dichotomy | 35 Search insert location
- 如何用Google Home音箱语音控制智汀家庭云设备?
猜你喜欢

获取省市区的名称【项目 商城】

qiankun 如何提取出公共的依赖库

Installation and use of numpy in pycharm

获取省市区列表【项目 商城】

Add MySQL path to system environment variable (win10)

Complex model machine experiment

Timestamp transform to standard time format

Introduction to 51 single chip microcomputer infrared communication

Obtain the name of the province or city 【 project mall 】
Example code of redis login registration
随机推荐
CSP 202112-1 sequence query (detailed explanation)
新建文档 bug,也可能是卡死了
Introduction to 51 single chip microcomputer UART serial port communication
Antinomy between brand and product
成为白帽大神 | 挑战 openGauss漏洞奖励计划
双指针 | 844. 比较含退格的字符串
Should a reliable and safe company open an account for US crude oil futures?
1. Getting started with pytorch
Open world how to design | Pascal Luban sharing notes
Boundary problems of regular expressions.
Windows version MySQL 8.0.28 installation and configuration method graphic tutorial
command
golang微服务实例Protobuf和Grpc的使用
电源管理(STM32)
Introduction to 51 single chip microcomputer infrared communication
How to use the salary management system?
Tips for college students' life: using tempermonkey to learn online lessons | check questions
2022年PMP考试的3A好考吗?秘籍奉上
Cat dog classification based on tensorflow
2022.6.9 C asynchronous