以下是使用 Vue 3 和 <script setup> 实现的代码示例,用于在输入 pinyin 时进行模糊查询,并提供候选项供选择。选择后,将对应数据的 name 添加到输入框中并加上逗号。代码中支持多选,可以选择多个候选项。

<template>
  <div>
    <a-input v-model="inputValue" @input="handleInput" />
    <a-select v-model="selectedItems" mode="multiple" style="width: 100%;" @change="handleSelect">
      <a-select-option v-for="item in filteredOptions" :key="item.code" :value="item.code">{{ item.name }}</a-select-option>
    </a-select>
  </div>
</template>

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

const hazardFactors = [
  { code: '1', name: 'Factor 1', pinyin: 'pinyin1' },
  { code: '2', name: 'Factor 2', pinyin: 'pinyin2' },
  { code: '3', name: 'Factor 3', pinyin: 'pinyin3' },
  // Add more hazard factors as needed
];

const inputValue = ref('');
const selectedItems = ref([]);

const filteredOptions = computed(() => {
  if (inputValue.value === '') {
    return [];
  }
  
  const pinyinRegex = new RegExp(inputValue.value, 'i');
  return hazardFactors.filter(factor => pinyinRegex.test(factor.pinyin));
});

function handleInput(value) {
  inputValue.value = value;
}

function handleSelect(selectedItems) {
  // Clear input value
  inputValue.value = '';
  
  // Get selected names
  const selectedNames = selectedItems.map(code => hazardFactors.find(factor => factor.code === code).name);
  
  // Assign selected names to input value with commas
  inputValue.value = selectedNames.join(', ');
}
</script>

以上代码中,hazardFactors 表示数据库表 hazard_factor 的数据,包含了 codenamepinyin 字段的模拟数据。inputValue 表示输入框的值,selectedItems 表示已选择的候选项的 code 数组。filteredOptions 是一个计算属性,根据输入的拼音进行模糊查询后的候选项列表。

handleInput 函数用于处理输入框的输入事件,更新 inputValue 的值。handleSelect 函数用于处理多选框的选择事件,将选择的候选项的 name 添加到 inputValue 中,并加上逗号。

模板部分使用了 <a-input> 输入框组件和 <a-select> 下拉选择框组件。通过 v-model 绑定数据,实现了输入框值和多选框选择的双向绑定。<a-select-option> 用于循环渲染候选项列表。

注意:上述代码中的 a-inputa-select 是基于 Ant Design Vue 组件库中的组件,你可以根据自己的组件库或需求进行调整

现有一数据库表hazard_factor有字段code、name及pinyin帮我编写代码使用a-input录入pinyin模糊查询并提供候选项选中后将对应数据的name赋值给a-input并加逗号在vue3中实现用《script setup》支持多选

原文地址: http://www.cveoy.top/t/topic/ibGi 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录