ant的select组件初始选中项且无法删除应当如何处理?


ant 的 select 组件初始选中项且无法删除应当如何处理?

代码示例:

<template>
  <div>
    <a-select
      mode="multiple"
      :value="selectedValues"
      @change="handleChange"
      style="width: 300px"
    >
      <a-select-option v-for="item in options" :key="item.value" :value="item.value">
        {{ item.label }}
      </a-select-option>
    </a-select>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';

// 选项定义
const options = [
  { label: 'Option 1', value: '1' },
  { label: 'Option 2', value: '2' },
  { label: 'Option 3', value: '3' }
];

// 初始选中的值
const initialSelectedValue = '1'; // 假设初始选中 Option 1
const selectedValues = ref([initialSelectedValue]); // 将初始选中项放入数组中

// 处理选择变化
const handleChange = (value) => {
  // 只允许删除非初始选中的项
  if (value.includes(initialSelectedValue)) {
    selectedValues.value = value; // 更新选中项,保留初始选中项
  } else {
    selectedValues.value = value; // 更新其他选中项
  }
};

// 监视 selectedValues,确保初始选中项始终存在
watch(selectedValues, (newValue) => {
  if (!newValue.includes(initialSelectedValue)) {
    selectedValues.value.push(initialSelectedValue); // 保证初始选中项存在
  }
});
</script>

文章作者: 冷杨威
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 冷杨威 !
  目录
-->