Vue如何基于JSON配置动态渲染分组下拉选择、复选框、日期选择器等表单组件
问题修复方案
核心问题梳理
你遇到的不生效问题由以下5个原因共同导致:
- 计算属性
getComputedJson构建分组时,仅透传了label和type两个字段,selection、date等组件渲染需要的字段全部丢失,自然无法触发对应组件的渲染判断 - JSON中复选框项的配置字段是
selection,但模板里判断复选框的条件是v-if="item.checkbox",字段完全不匹配 - 最后一条日期组件的分组字段拼写错误为
gruppe,代码读取item.group时拿不到分组值,导致该组件被丢弃 - 表格结构不符合规范,
<tr>标签下直接嵌套<div>会被浏览器解析异常,组件渲染逻辑可能错乱 - BootstrapVue的
<b-form-select>、<b-form-checkbox-group>默认要求选项配置同时有text(显示文本)和value(绑定值)字段,你现有配置仅含text,会导致选项展示或绑定异常
修复步骤
第一步:修正JSON配置
先修正字段拼写和不匹配的问题,也可以直接在代码里做兼容,这里优先修正配置:
[ { "label": "Input 1", "type": "text", "group": "Test1" }, { "label": "Input 2", "type": "text", "group": "Test2" }, { "label": "Input 3", "type": "text", "group": "Test3" }, { "label": "Input 4", "type": "number", "group": "Test1" }, { "label": "Selection", "selection": [ { "value": "1", "text": "Selection 1" }, { "value": "2", "text": "Selection 2" }, { "value": "3", "text": "Selection 3" } ], "group": "Test2" }, { "label": "Checkbox", "checkbox": [ { "value": "1", "text": "Checkbox 1" }, { "value": "2", "text": "Checkbox 2" }, { "value": "3", "text": "Checkbox 3" } ], "group": "Test1" }, { "label": "Date", "date": "yes", "group": "Test3" } ]
调整点:修正日期分组字段拼写、复选框配置字段改为checkbox、所有选项补全value字段
第二步:修正计算属性逻辑
用对象展开运算符透传所有字段,不需要手动逐个声明,同时兼容错误拼写的分组字段:
<script> export default { computed: { getComputedJson() { const computedJson = {}; this.json.forEach(item => { // 兼容拼写错误的gruppe字段 const groupKey = item.group || item.gruppe if(!computedJson[groupKey]) { computedJson[groupKey] = []; } // 展开item透传所有字段,不需要手动拼接 computedJson[groupKey].push({...item}); }) return computedJson; } } } </script>
第三步:修正模板代码
修复表格结构,同时给选择类组件声明文本字段:
<table> <tbody> <tr v-for="(group, key) in getComputedJson" :key="key"> <!-- 补充td标签符合表格结构规范 --> <td> <div v-for="(item, indexer) in group" :key="indexer"> <b-form-input v-if="item.type" :type="item.type"></b-form-input> <b-form-select v-if="item.selection" :options="item.selection" text-field="text" value-field="value"></b-form-select> <b-form-checkbox-group v-if="item.checkbox" :options="item.checkbox" text-field="text" value-field="value"></b-form-checkbox-group> <b-form-datepicker v-if="item.date"></b-form-datepicker> </div> </td> </tr> </tbody> </table>
内容的提问来源于stack exchange,提问作者user16365685
相关产品推荐
相关产品推荐

