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%"
/>