Vxe-table编辑表格插槽input框,选项lable显示,选中是value问题解决
在使用Vxe-table编辑表格组件时,是利用插槽的方式,把select下拉框嵌套进去。在做项目时,前端页面需要显示选项名称,但由于组件的问题,移走或关闭单元格(cell)的激活状态,此单元格会显示option的value而不是label如图所示:
- 选中前:
- 选中后:
1、通过官方文档的方式解决前端展示label,传参value给后端
如果选项值是固定,通过if…else if…或者switch…case…进行判断转换,演示代码如下:
//选项下拉值接口,后端返回的数据格式
const optionTypeMappings = [
{ label: '输入框', dictValue: '10' },
{ label: '单选', dictValue: '20' },
{ label: '多选', dictValue: '30' },
{ label: '上传文件', dictValue: '40' },
{ label: '日期',dictValue: '50' },
];
//定义一个数组(获取到表格内容的值)
const Lists = [
{ option_id: 0,question_id: 0, option_type: '输入框' },
{ option_id: 0,question_id: 0,option_type: '单选' }
];
//循环遍历,进行label替换成value
Lists.forEach((element) => {
const optionType = String(element.option_type); // 将 label转换为字符串
switch (optionType) {
case '输入框':
element.option_type = '10';
break;
case '单选':
element.option_type = '20';
break;
case '多选':
element.option_type = '30';
break;
case '上传文件':
element.option_type = '40';
break;
case '日期':
element.option_type = '50';
break;
case '总分':
element.option_type = '60';
break;
case '组合':
element.option_type = '70';
break;
default:
// 对于未匹配到的值,可以按需进行处理,例如保留原值或抛出错误等
break;
}
});
输入打印结果:
console.log('Lists', Lists);
/*[
{
"option_id": 0,
"question_id": 0,
"option_type": "10"
},
{
"option_id": 0,
"question_id": 0,
"option_type": "20"
}
]*/
2、通过一对一的方式,使用reduce函数将映射数组转换为查找对象
通过上述的方法,如果下拉框的接口内容有变动,我们定义的输入框,单选等字段内容就需要进行手动更改变动。本身上述的代码就非常的冗余,这时候就需要进行代码优化,利用js方法来减少代码的工作量,代码示例如下:
//选项下拉值接口,后端返回的数据格式
const optionTypeMappings = [
{ label: '输入框', dictValue: '10' },
{ label: '单选', dictValue: '20' },
{ label: '多选', dictValue: '30' },
{ label: '上传文件', dictValue: '40' },
{ label: '日期',dictValue: '50' },
];
//定义一个数组(获取到表格内容的值)
const Lists = [
{ option_id: 0,question_id: 0,option_type: '输入框'},
{ option_id: 0,question_id: 0,option_type: '单选'}
];
// 使用reduce函数将映射数组转换为查找对象
const optionTypeLookup = optionTypeMappings.reduce((lookup, item) =>
{
lookup[item.label] = item.dictValue;
return lookup;
}, {});
// 遍历Lists数组,使用查找对象更新option_type
Lists.forEach((element) =>
{
const optionType = String(element.option_type); // 确保它是一个字符串
// 使用查找对象获取对应的value,如果找不到匹配项,则保留原来的option_type
element.option_type = optionTypeLookup[optionType] || element.option_type;
});
输入打印结果:
console.log('optionTypeLookup', optionTypeLookup);
{
"输入框": "10",
"单选": "20",
"多选": "30",
"上传文件": "40",
"日期": "50"
}
console.log('Lists', Lists);
[
{
"option_id": 0,
"question_id": 0,
"option_type": "10"
},
{
"option_id": 0,
"question_id": 0,
"option_type": "20"
}
]
通过Array.prototype.reduce()很好的解决了固定选项内容的问题,不管后端是否怎么更改label,都会有起值对应。
reduce() 方法对数组中的每个元素按序执行一个提供的 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。