将元素添加到最初不在下拉列表中的可搜索下拉列表 - Vue
Add Elements to a Searchable Dropdown That Weren't Originally in the Dropdown - Vue
如何使用 Vue 将输入框添加到 select
元素中?
假设我有一个像 ['Red', 'Yellow', 'Green']
这样的列表,用户想要选择列表中没有的 'Black'。
我希望用户能够在 select 元素中键入它,将其添加到列表中,然后 selected。
到目前为止,这是我的代码:
<template>
<div >
<div class="form-group col-md-2">
<label >Colors</label>
<select v-model="selected" class="form-control" >
<option v-for="option in list" class="form-control" :key="option">
{{ option}}
</option>
</select>
</div>
<p>The selected color is: {{selected}}</p>
</div>
</template>
<script>
export default {
data(){
return{
list:['Red', 'Yellow', 'Green'],
selected: '',
};
},
}
</script>
您可以使用 vue-multiselect
作为可搜索下拉菜单:
<multiselect
:options="list"
v-model="selected"
></multiselect>
...并添加一些自定义代码以在 Enter 或 Return[=31 时将键入的颜色添加到 list
=] 被按下:
<div @keyup.enter="addColor($event)">
<multiselect
:options="list"
v-model="selected"
@search-change="typed = $event"
></multiselect>
</div>
addColor() {
if (!this.list.includes(this.typed)) this.list.push(this.typed); // check if inputted color is already in the list; if not, add it; if so, don't
this.selected = this.typed; // set `selected` to the currently typed color
},
请注意,您必须为 vue-multiselect 添加 CSS,您可以在安装说明中查看如何操作 here。
如何使用 Vue 将输入框添加到 select
元素中?
假设我有一个像 ['Red', 'Yellow', 'Green']
这样的列表,用户想要选择列表中没有的 'Black'。
我希望用户能够在 select 元素中键入它,将其添加到列表中,然后 selected。
到目前为止,这是我的代码:
<template>
<div >
<div class="form-group col-md-2">
<label >Colors</label>
<select v-model="selected" class="form-control" >
<option v-for="option in list" class="form-control" :key="option">
{{ option}}
</option>
</select>
</div>
<p>The selected color is: {{selected}}</p>
</div>
</template>
<script>
export default {
data(){
return{
list:['Red', 'Yellow', 'Green'],
selected: '',
};
},
}
</script>
您可以使用 vue-multiselect
作为可搜索下拉菜单:
<multiselect
:options="list"
v-model="selected"
></multiselect>
...并添加一些自定义代码以在 Enter 或 Return[=31 时将键入的颜色添加到 list
=] 被按下:
<div @keyup.enter="addColor($event)">
<multiselect
:options="list"
v-model="selected"
@search-change="typed = $event"
></multiselect>
</div>
addColor() {
if (!this.list.includes(this.typed)) this.list.push(this.typed); // check if inputted color is already in the list; if not, add it; if so, don't
this.selected = this.typed; // set `selected` to the currently typed color
},
请注意,您必须为 vue-multiselect 添加 CSS,您可以在安装说明中查看如何操作 here。