我有一个表单组件,如下所示:
<form-component>
<text-component name="test1" />
<select-component name="test2" />
</form-component>
我需要 FormComponent 才能在每个子项周围应用包装器 div
从上面的代码来看,FormComponent 的输出应该是这样的:
<form>
<div class="mb-3">
<text-component name="test1" />
</div>
<div class="mb-3">
<select-component name="test2" />
</div>
</form>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
这是一种解决方法:
const formChildren = [{ name: 'test1', is: TextComponent }, { name: 'test2', is: SelectComponent }]FormComponent.vue
<template> <form> <div v-for="(child, index) in children" :key="index" class="mb-3" > <component v-bind="child" /> </div> </form> </template> <script setup> defineProps(['children']) </script>这是工作演示 您在评论中提出的建议,循环遍历
$slots.default()的内容。如果您更喜欢用模板语法编写逻辑,那就是正确的方法,我认为这没有什么问题。
我个人更喜欢第一种方法,因为我的倾向是(通常)将模板语法限制到最少。将组件保留在对象或映射结构中使我能够进行精细控制并自动执行任务,例如:
我的偏好可能来自于在配置驱动的环境中进行了大量工作,其中业务逻辑通常存储在对象中。用模板语法编写它并没有什么问题,但总的来说,我发现它有限制。