用vue3和ts写一个支持可输入、可全选的下拉框,多选的值在输入框中用英文逗号隔开
时间: 2023-05-13 22:05:47 浏览: 279
vue-select 多选下拉列表
5星 · 资源好评率100%
以下是一个基于 Vue3 和 TypeScript 的可输入、可全选的下拉框的示例代码:
```html
<template>
<div class="dropdown">
<input
type="text"
class="dropdown-input"
v-model="inputValue"
@focus="showDropdown = true"
@blur="hideDropdown"
@keydown.enter.prevent="addValue"
@keydown.down.prevent="highlightNext"
@keydown.up.prevent="highlightPrev"
@keydown.delete="deleteValue"
@keydown.backspace="deleteValue"
/>
<div v-if="showDropdown" class="dropdown-menu">
<div
v-for="(option, index) in filteredOptions"
:key="option.value"
:class="{ 'dropdown-option': true, 'highlighted': index === highlightedIndex }"
@mousedown.prevent="addValue(option)"
>
{{ option.label }}
</div>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent, ref, computed } from 'vue';
interface Option {
label: string;
value: string;
}
export default defineComponent({
name: 'Dropdown',
props: {
options: {
type: Array as () => Option[],
required: true,
},
value: {
type: String,
default: '',
},
},
setup(props, { emit }) {
const inputValue = ref(props.value);
const showDropdown = ref(false);
const highlightedIndex = ref(-1);
const filteredOptions = computed(() =>
props.options.filter(
(option) =>
option.label.toLowerCase().indexOf(inputValue.value.toLowerCase()) !== -1
)
);
const addValue = (option?: Option) => {
if (!option) {
option = { label: inputValue.value, value: inputValue.value };
}
emit('input', option.value);
inputValue.value = '';
hideDropdown();
};
const deleteValue = () => {
if (inputValue.value === '') {
const values = props.value.split(',');
values.pop();
emit('input', values.join(','));
}
};
const highlightNext = () => {
if (highlightedIndex.value < filteredOptions.value
阅读全文