要将你的 Vue 组件中的多选功能改为单选功能,可以进行如下调整。以下是修改后的代码:
调整步骤
- 删除
v-model:selected-keys
的绑定:我们不需要单独管理已选择的项,因为它们会与目标键相同。 - 更新
handleChange
方法:当用户尝试选择一个新项目时,我们只需设置targetKeys
为该项目的键。 - 移除任何对多个项目处理的逻辑。
更新后的代码
<template>
<div class="singleMarking">
<div class="cancel-btn-container">
<a-button class="cancel-btn" @click="handleCancel">x</a-button>
</div>
<div style="margin-top: 40px">
<a-transfer
v-model:target-keys="targetKeys"
:data-source="dataSource"
:titles="['待选状态', '已选状态']"
:render="renderItem"
@change="handleChange"
list-style="width: 100%;height:300px;overflow-y: auto;"
/>
</div>
<div class="action-btns">
<a-button class="cancel-btn" @click="handleCancel">取消</a-button>
<a-button class="confirm-btn" type="primary" @click="handleConfirm">确认</a-button>
</div>
</div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { useRoute } from 'vue-router';
import { queryTagList, getCustomerTags, singleCustomerTags } from '@/utils';
const formState = reactive({});
const targetKeys = ref([]); // 用于存储当前选择的标签
const route = useRoute();
const custId = ref('');
const name = ref('');
const dataSource = ref([]);
const handleCancel = () => {
window.parent.postMessage({ type: 'close-dialog', action: 'cancel' }, '*');
};
const handleChange = (nextTargetKeys) => {
// 单选时,直接赋值为当前选中的目标键
targetKeys.value = nextTargetKeys.length > 0 ? [nextTargetKeys[0]] : [];
};
const handleConfirm = () => {
const params = {
tagsId: targetKeys.value,
customerId: custId.value,
customerName: name.value
};
singleCustomerTags(params).then((response) => {
if (response.success) {
message.success(response.message);
} else {
message.error(response.message);
}
handleCancel();
});
};
const fetchAvailableTags = () => {
queryTagList().then((response) => {
if (response.success) {
dataSource.value = response.data.map((tag) => ({
key: tag.id,
title: tag.tagsDescription,
color: tag.color || '#000'
}));
} else {
message.error(response.message);
}
});
};
const fetchSelectedTags = () => {
getCustomerTags({ customerId: custId.value }).then((response) => {
if (response.success) {
selectedKeys.value = response.data.map((tag) => tag.id);
targetKeys.value = response.data.length > 0 ? [response.data[0].id] : []; // 默认选择第一个
} else {
message.error(response.message);
}
});
};
onMounted(() => {
custId.value = route.query.custId;
name.value = route.query.name;
fetchAvailableTags();
fetchSelectedTags();
});
</script>
修改说明
handleChange
函数现在仅接受新目标键列表并将其设置为单一值(如果有的话)。- 如果没有被选择,则清空
targetKeys
。 - 在获取已选择标签 (
fetchSelectedTags
) 时,如果存在已选择的标签,默认仅保留第一个。
这样,你就实现了一个单选框功能。用户在点击不同的项时,只能保持一个被选中状态。
内容由零声教学AI助手提供,问题来源于学员提问