qiankun
props动态值
import { initGlobalState } from 'qiankun'; // 初始化全局状态 const actions = initGlobalState({ name: '张三', }); // 注册子应用时把 actions 传过去 registerMicroApps([ { name: 'subapp', entry: 'http://localhost:7001', container: '#container', activeRule: '/subapp', props: actions, // 关键 }, ]); start(); // 主应用改数据 setTimeout(() => { actions.setGlobalState({ name: '李四' }); }, 2000);在 mount 里监听: export async function mount(props) { // 监听变化 props.onGlobalStateChange((state) => { console.log('子应用感知到数据变了:', state); // 这里更新子应用页面/state 即可 }, true); } state当前全局状态里的所有数据 initGlobalState 里存啥 → state就是啥!import { initGlobalState } from 'qiankun' const state = { user: '张三', theme: 'dark' } const actions = initGlobalState(state) // 注册子应用时把 actions 放进 props props: { actions }export async function mount(props) { // 监听变化 props.actions.onGlobalStateChange((state) => { console.log(state) }) // 修改状态 props.actions.setGlobalState({ user: '李四' }) }Vue.prototype.$xxx
Vue.prototype.$user = { name: '张三' } Vue.prototype.$getScore = () => 100 template 里不能直接写 <$user> export default { mounted() { console.log(this.$user.name) console.log(this.$getScore()) } }import MyButton from '@/components/MyButton.vue' Vue.prototype.$MyButton = MyButton 只能在 template 里当组件用 <$MyButton> script 里一般不用 this.$MyButton <template> <div> <$MyButton type="primary" @click="handle" /> </div> </template>子应用
子应用怎么渲染?
mount(props) 调用 render(props)里面执行:
new Vue({ … }).$mount(‘#app’)
import Vue from 'vue' import App from './App.vue' import router from './router' let instance = null; // 子应用实例 // ============ 渲染函数(抽出来,方便多次调用)============ function render(props) { // 监听主应用状态 props.onGlobalStateChange((newState) => { console.log('主应用数据变了:', newState); // 你可以在这里更新子应用的 data/vuex // 比如: // store.commit('setUser', newState.userName) }, true); // 渲染子应用 instance = new Vue({ router, render: h => h(App), }).$mount('#app'); // 挂载到自己的 #app } // ============= 生命周期:qiankun 会调用 ============= export async function bootstrap() { console.log('子应用启动'); } // 挂载时 export async function mount(props) { console.log('子应用挂载,接收 props:', props); render(props); // ✅ 在这里渲染! } // 卸载时 export async function unmount() { instance.$destroy(); instance.$el.innerHTML = ''; instance = null; } // 独立运行(非 qiankun 环境) if (!window.__POWERED_BY_QIANKUN__) { render({}); }