优化自定义属性选项数据处理逻辑,支持对象数组与字符串数组双向转换

This commit is contained in:
WUSIJIAN
2025-12-16 18:01:32 +08:00
parent 457a4a091d
commit 4e7cf02029

View File

@@ -276,9 +276,10 @@ const openDialog = (row?: CategoryRow | string, edit?: boolean) => {
ruleForm.name = data.name || '';
ruleForm.sort = data.sort || 0;
ruleForm.status = data.status || 'enabled';
// 处理 attrs 中的 options 字段(后端可能返回字符串格式)
// 处理 attrs 中的 options 字段
ruleForm.attrs = (data.attrs || []).map((attr: any) => {
let options = attr.options;
// 后端可能返回字符串格式,先解析
if (typeof options === 'string') {
try {
options = JSON.parse(options);
@@ -286,6 +287,11 @@ const openDialog = (row?: CategoryRow | string, edit?: boolean) => {
options = [];
}
}
// 如果是对象数组 [{label, value}],转换为简单数组 [value]
// 这样前端选择器才能正确工作
if (Array.isArray(options) && options.length > 0 && typeof options[0] === 'object') {
options = options.map((opt: any) => opt.value || opt.key || opt);
}
return { ...attr, options: options || [] };
});
// 如果有单选/多选属性,预加载字典类型数据
@@ -321,15 +327,24 @@ const onSubmit = () => {
const processedAttrs = ruleForm.attrs.map((attr) => {
if (attr.type === 'select' || attr.type === 'multi_select') {
const { name, ...rest } = attr;
// 将 options 从 ["red"] 转换为 [{"label":"红色","value":"red"}]
const options = attr.options || [];
let formattedOptions: any[] = [];
// 判断 options 是否已经是对象数组格式
if (options.length > 0 && typeof options[0] === 'object') {
// 已经是对象数组格式,直接使用
formattedOptions = options;
} else {
// 是字符串数组,需要转换为 [{label, value}] 格式
const dictValues = getDictValuesByType(attr.description || '');
const formattedOptions = (attr.options || []).map((optValue: string) => {
formattedOptions = options.map((optValue: string) => {
const dictItem = dictValues.find((d: any) => d.key === optValue);
return {
label: dictItem?.value || optValue,
value: optValue,
};
});
}
return { ...rest, options: formattedOptions };
}
return attr;