el-select按指定位置插入
el-select默认不支持像文本一样鼠标点击在哪里就往当前鼠标点击的位置插入数据,本次优化为:可在点击的标签之后插入位置已模拟实现按指定位置插入数据
<div class="custom-select-container">
<el-select
v-model="selectedItems"
multiple
filterable
placeholder="请选择商品"
class="custom-multi-select"
@click="handleSelectClick"
@remove-tag="handleTagRemove"
>
<el-option
v-for="item in filteredOptions"
:key="item.id"
:label="`${item.name} (${item.status})`"
:value="item.id"
@click.stop="handleOptionClick(item.id)"
/>
</el-select>
</div>
// 模拟商品数据
const allOptions = ref([
{ id: '4718061603911081984', name: 'a1', status: '已上架' },
{ id: '4718065314762825728', name: 'a2', status: '已下架' },
{ id: '5718061603911081984', name: 'a3', status: '已上架' },
{ id: '6718065314762825728', name: 'a6', status: '已上架' },
]);
const selectedItems = ref([]);
const searchQuery = ref('');
const insertPosition = ref(null); // 记录插入位置
const lastAddedItem = ref(null); // 记录最后添加的项
// 处理选择框点击事件
const handleSelectClick = (event) => {
const tags = document.querySelectorAll('.custom-multi-select .el-tag');
let foundIndex = -1;
tags.forEach((tag, index) => {
const rect = tag.getBoundingClientRect();
if (
event.clientX >= rect.left &&
event.clientX <= rect.right &&
event.clientY >= rect.top &&
event.clientY <= rect.bottom
) {
foundIndex = index;
}
});
insertPosition.value = foundIndex;
};
// 处理标签移除事件
const handleTagRemove = (tag) => {
// 这里可以添加移除标签时的逻辑
};
// 监听selectedItems变化
watch(selectedItems, (newVal, oldVal) => {
// 只有当lastAddedItem有值时才处理位置插入
if (lastAddedItem.value && newVal.includes(lastAddedItem.value)) {
// 新添加的项总是在最后,我们需要把它移到正确的位置
if (insertPosition.value !== null && insertPosition.value !== -1) {
const itemToMove = lastAddedItem.value;
const newArray = newVal.filter(id => id !== itemToMove);
newArray.splice(insertPosition.value + 1, 0, itemToMove);
selectedItems.value = newArray;
}
}
// 重置状态
lastAddedItem.value = null;
insertPosition.value = null;
}, { deep: true });
// 自定义选项点击处理
const handleOptionClick = (itemId) => {
lastAddedItem.value = itemId;
};
// 过滤选项
const filteredOptions = computed(() => {
return allOptions.value.filter(item =>
item.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
item.id.includes(searchQuery.value)
);
});
您还未登录, 登录 后可进行评论
发表
还没有评论哦,来抢个沙发吧!