如何让v-for循环中动态生成的表单元素实现横向并排展示
根因说明
你之前给外层加row不生效的原因是:Bootstrap的row仅声明flex容器属性、调整边距,但是你循环生成的子div默认是块级元素,宽度占满100%父容器,所以还是会垂直堆叠。
实现方案
方案1:用Bootstrap内置工具类(适配你当前的BootstrapVue技术栈)
直接在外层容器添加flex相关工具类即可:
<!-- d-flex开启flex布局,flex-wrap超出容器宽度自动换行,gap-2设置表单项间距 --> <div class="d-flex flex-wrap gap-2"> <div v-for="(item, index) in json" :key="index"> <b-form-input v-if="item.type" :type="item.type"></b-form-input> </div> </div>
如果需要避免输入框被挤压过窄,可以给子元素补充最小宽度样式:
<div class="d-flex flex-wrap gap-2"> <div class="form-item" v-for="(item, index) in json" :key="index"> <b-form-input v-if="item.type" :type="item.type"></b-form-input> </div> </div> <style> .form-item { min-width: 180px; /* 可根据业务需求调整数值 */ } </style>
方案2:自定义CSS实现(不依赖Bootstrap类)
完全自己写布局样式,兼容性更强:
<div class="form-container"> <div v-for="(item, index) in json" :key="index"> <b-form-input v-if="item.type" :type="item.type"></b-form-input> </div> </div> <style> .form-container { display: flex; flex-wrap: wrap; gap: 12px; /* 统一控制表单项的横向、纵向间距 */ } /* 可选:设置每个表单项的最小宽度 */ .form-container > div { min-width: 180px; } </style>
内容的提问来源于stack exchange,提问作者patrick96
相关产品推荐
相关产品推荐

