Vue中如何直接向插槽组件传递响应式Props并保持响应性?
问题:如何从App.vue向ParentComponent插槽内的子组件传递响应式Props
需求:直接从App.vue向插槽内的ChildComponent传递响应式Props,无需通过ParentComponent中转,且修改App.vue数据时ChildComponent的Props能实时更新。当前代码中修改App.vue数据后,ChildComponent的Props无变化,核心原因是ParentComponent提前缓存了插槽VNode导致响应性丢失。
原代码问题分析
ParentComponent在setup阶段直接调用slots.default()获取插槽VNode并缓存,该操作仅执行一次。后续App.vue中的响应式数据变化时,不会重新生成新的VNode,因此ChildComponent的Props无法同步更新。
解决方案
修改ParentComponent.vue
移除手动缓存VNode的逻辑,让Vue模板系统自动处理插槽渲染,确保响应式依赖被正确跟踪:
<script setup lang="ts"> import { ref } from "vue" const currentStep = ref(0) </script> <template> <div> <transition mode="out-in"> <keep-alive> <suspense> <!-- 遍历插槽内容,根据currentStep显示对应项 --> <template v-for="(slotNode, index) in $slots.default()" :key="index"> <component :is="slotNode" v-if="index === currentStep" /> </template> </suspense> </keep-alive> </transition> </div> </template>
修正ChildComponent.vue的语法错误
原代码中defineProp应为defineProps:
<script setup lang="ts"> const props = defineProps({ msg: String }) </script> <template> <div>{{ props.msg }}</div> </template>
修正App.vue的绑定错误
将模板中data改为对应响应式变量:
<script setup lang="ts"> import { ref } from "vue" const data1 = ref("123") const data2 = ref("456") const data3 = ref("789") </script> <template> <parent-component> <child-component :msg="data1"/> <child-component :msg="data2"/> <child-component :msg="data3"/> </parent-component> </template>
原理说明
通过在模板中使用$slots.default()遍历插槽内容,Vue会在响应式数据变化时重新执行插槽渲染逻辑,生成新的VNode并传递最新的Props值,从而保证ChildComponent的Props能够实时响应App.vue中的数据变化,同时避免了手动缓存VNode导致的响应性丢失问题。
内容的提问来源于stack exchange,提问作者s16777216
相关产品推荐
相关产品推荐

