在你的代码中,fetchSelectedTags
函数的目的是获取已选标签,并将它们设置为 selectedKeys
和 targetKeys
。如果左侧的可选项(dataSource)和右侧的已选项(selectedKeys)之间存在不匹配,你可以尝试以下步骤来确保已选择的标签能够正确显示在“已选状态”框中。
解决方案
确保数据源一致性: 确保你在调用
fetchSelectedTags
方法之前已经成功地获取了所有可能的标签数据。在使用a-transfer
组件时,左侧的数据源 (dataSource
) 应该包含右侧 (已选状态) 的数据。修改 renderItem: 确保 renderItem 能够正确渲染有颜色属性的项目。
更新 selectedKeys 和 targetKeys: 当从后端获取到客户标签数据后,遍历 dataSource 数据,根据每个 tag ID 判断其是否出现在 selectedKeys 中。这样可以保证当页面加载时,只要存在对应的数据,就能够在已选框中展示相应的标签。
修改代码示例
const fetchAvailableTags = () => {
queryTagList().then((response) => {
if (response.success) {
dataSource.value = response.data.map((tag) => ({
key: tag.id,
title: tag.tagsDescription,
color: tag.color || '#000',
}));
// 需要在这里根据当前 tagsId 更新 selectedKeys 和 targetKeys
updateSelectedAndTargetKeys();
} else {
message.error(response.message);
}
});
};
const updateSelectedAndTargetKeys = () => {
const existingIds = new Set(dataSource.value.map(tag => tag.key));
// 更新 selectedKeys 和 targetKeys
const matchedIds = existingIds.forEach(id => {
if (selectedKeys.value.includes(id)) {
targetKeys.value.push(id); // 将匹配到的 id 添加到 targetKeys 中
}
});
// 如果没有匹配 id,需要清空或做处理。
};
// fetchSelectedTags 不需要更改,但一定要确保是在获得 dataSource 后调用。
const fetchSelectedTags = () => {
getCustomerTags({ customerId: custId.value }).then((response) => {
if (response.success) {
selectedKeys.value = response.data.map((tag) => tag.id);
updateSelectedAndTargetKeys(); // 在这里根据更新后的 dataSource 来更新目标
} else {
message.error(response.message);
}
});
};
总结
- 确保你在执行选择操作之前已经加载了所有数据。
- 将获取到的已选标签与可用标签进行比对,以便正确反映它们之间的关系。
- 如果有多个状态需要同步,请考虑使用 computed 属性来减少重复代码。这样一来,你就能保持数据的一致性并且简化逻辑。
内容由零声教学AI助手提供,问题来源于学员提问