Vue3 - provide 提供的异步数据 inject 得到的数据 undefined 或 null

发布时间 2023-09-27 17:08:58作者: Himmelbleu

如下所示,父组件(祖先组件)通过 provide 函数向所有后代组件传递 prop。但是这两个 Ref 类型的数据最开始没有,需要等到 onMounted 初始化之后才有值。此时会遇到两个问题

  1. 后代组件在 setup 函数中或者 onBeforeMount 等非常周期中调用,可能获取的是 undefined 或者 null。
  2. 传递响应式数据(Ref)时,如下例子,通过 .value 传递非 Ref 类型数据下去,导致后代组件不会更新数据,始终获取的最开始的值。
file:[Father.vue]
const paper = shallowRef<dia.Paper>();
const graph = shallowRef<dia.Graph>();

lit:[provide("bleuonPaper", paper.value);
provide("bleuonGraph", graph.value);]:lit

onMounted(() => {
  const jointjs = initJointJs({
    el: "bleuon__flowchat-content",
    width: "85vw",
    height: "75vh",
    bgColor: "#ffffff"
  });
});
file:[Child.vue]
const paper = inject("bleuonPaper");