chore: 使用 provide 实现上下文共享

This commit is contained in:
wangxuefeng 2025-03-31 11:30:50 +08:00
parent a64433e57b
commit 6b2c7bad00
2 changed files with 41 additions and 32 deletions

View File

@ -5,6 +5,8 @@ import {
getCurrentInstance,
onBeforeUnmount,
onMounted,
provide,
reactive,
ref,
watch,
} from 'vue';
@ -243,7 +245,23 @@ const notifyParent = (event: string, data?: any) => {
}
};
// wujie props initParams
//
const contextRef = ref(null);
//
const initContext = () => {
if (!isValidParams(initParams.value)) return;
contextRef.value = reactive({
...initParams.value,
updateTimestamp: Date.now(),
});
};
//
provide('lowCodeContext', contextRef);
// wujie props
const setupWujiePropsWatcher = () => {
if (!isWujieSubApp) return;
@ -266,17 +284,31 @@ const setupWujiePropsWatcher = () => {
//
prevPropsSnapshot = currentPropsSnapshot;
// props
// props
const newProps = JSON.parse(currentPropsSnapshot);
const oldParams = initParams.value;
//
// initParams
initParams.value = {
...newProps,
_timestamp: Date.now(), //
_timestamp: Date.now(),
};
console.log('initParams 已更新为新对象:', initParams.value);
//
if (contextRef.value) {
// 使 Object.assign
Object.assign(contextRef.value, {
...newProps,
updateTimestamp: Date.now(),
});
console.log('上下文已更新:', contextRef.value);
//
if (isWujieSubApp) {
window.$wujie.bus.$emit('context-updated', contextRef.value);
}
}
//
if (
@ -286,38 +318,15 @@ const setupWujiePropsWatcher = () => {
) {
console.log('核心参数发生变化,重新加载组件');
reloadComponent();
} else {
// 使
forceUpdateRenderer();
}
}
}, 300);
//
onBeforeUnmount(() => {
clearInterval(intervalId);
});
};
//
const forceUpdateRenderer = () => {
if (renderer.value && typeof renderer.value.update === 'function') {
// update
console.log('调用渲染器的 update 方法');
renderer.value.update(initParams.value);
} else {
//
console.log('强制刷新渲染器组件');
const temp = renderer.value;
renderer.value = null;
//
setTimeout(() => {
renderer.value = temp;
}, 0);
}
};
//
const reloadComponent = async () => {
if (!isValidParams(initParams.value)) {
@ -389,6 +398,9 @@ onMounted(async () => {
if (isWujieSubApp) {
notifyParent('render-success');
//
initContext();
// wujie props
setupWujiePropsWatcher();
}
@ -411,9 +423,7 @@ onMounted(async () => {
<component
:is="renderer"
v-if="renderer"
:key="initParams?._timestamp || 'default'"
:ctx-props="initParams"
v-bind="initParams"
:ctx-props="contextRef"
style="width: 100%; height: 100%"
/>

View File

@ -26,7 +26,6 @@ const props = withDefaults(
projectId: number;
route?: RouteRecordRaw;
router?: Router;
searchParams?: Record<string, any>;
sync?: boolean;
url?: string;
}>(),