preface

This project is a vue2 base + Vue2 module Federation + VUe3 sub-application, which needs to solve the vuEX data sharing between vuE2 base and VUe3 sub-application. Ideas: InitGlobalState in Qiankun is used to generate a shared data. SetGlobalState and onGlobalStateChange methods are passed to the sub-application to enable the sub-application to modify the shared data and listen to changes in the shared data. Subapplications use onGlobalStateChange to modify data in their VUEX.

implementation

// Base import {initGlobalState} from 'qiankun'; // Initialize shared data const {onGlobalStateChange} = initGlobalState({value: '1'}) onGlobalStateChange((state, prev) => { // state: Console. log('main-app onGlobalStateChange', state, prev)})Copy the code
Js import {createStore} from 'vuex' import cloneDeep from 'lodash/cloneDeep'; const state = { store: {} } const getters = { value: state => state.store.value } const mutations = { initStore(state, data) { state.store = data }, setStore(state, datay) { state.store = { ... state.store, ... data } } } const actions = { increment ({ commit }) { commit('setStore', { value: '2' }) } } const initStore = { actions, getters, state, mutations, modules: {}, strict: false, plugins: []. } function initStore(props) {const QiankunDataSharePlugin = (store) => {let prevState = cloneDeep(store.state) // When Store is called after initialization, using the vuex plug-in to listen for every data change, Store. Subscribe ((mutation, State) => {// call const nextState = cloneDeep(state) after each mutation. If (json.stringify (nextState)! Stringify (nextState)! == json.stringify (prevState)) {prevState = nextState // after store change in microapp, Update status to the main application props. SetGlobalState && props. SetGlobalState ({... state.store}) } }) } const storeInstance = createStore({ ... initStore, plugins: // After the main application status changes, Synchronization to micro used props. The onGlobalStateChange && props. OnGlobalStateChange ((state, prev) = > {storeInstance.com MIT (' initStore ', state) console.log('vue3-app onGlobalStateChange', state, prev) }, true ) return storeInstance } export default initStore; // main.js let instance = null; Export async function mount(props) {render(props); instance.config.globalProperties.$onGlobalStateChange = props.onGlobalStateChange; instance.config.globalProperties.$setGlobalState = props.setGlobalState; } // If it is a universe application, execute if (! window.__POWERED_BY_QIANKUN__) { render(); } // The key is store(props), Function render(props) {const {container} = props; instance = createApp(App); instance.use(store(props)).mount(container ? container.querySelector('#app') : '#app'); }Copy the code