vue实现select
Vue 实现 Select 组件的方法
使用原生 HTML <select> 与 Vue 绑定
通过 v-model 实现双向数据绑定,适用于简单场景:
<template>
<select v-model="selectedOption">
<option disabled value="">请选择</option>
<option v-for="option in options" :key="option.value" :value="option.value">
{{ option.text }}
</option>
</select>
</template>
<script>
export default {
data() {
return {
selectedOption: '',
options: [
{ value: '1', text: '选项1' },
{ value: '2', text: '选项2' }
]
}
}
}
</script>
自定义 Select 组件
实现更复杂的交互和样式控制:
<template>
<div class="custom-select" @click="toggleDropdown">
<div class="selected-option">
{{ selectedOption.text || '请选择' }}
</div>
<ul v-show="isOpen" class="dropdown">
<li
v-for="option in options"
:key="option.value"
@click="selectOption(option)"
>
{{ option.text }}
</li>
</ul>
</div>
</template>
<script>
export default {
props: {
options: {
type: Array,
required: true
}
},
data() {
return {
isOpen: false,
selectedOption: {}
}
},
methods: {
toggleDropdown() {
this.isOpen = !this.isOpen
},
selectOption(option) {
this.selectedOption = option
this.$emit('input', option.value)
this.isOpen = false
}
}
}
</script>
<style>
.custom-select {
position: relative;
width: 200px;
}
.dropdown {
position: absolute;
width: 100%;
border: 1px solid #ddd;
max-height: 200px;
overflow-y: auto;
}
</style>
使用第三方组件库
推荐使用成熟的 UI 库快速实现:
-
Element UI:
<el-select v-model="value" placeholder="请选择"> <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option> </el-select> -
Ant Design Vue:
<a-select v-model="value" style="width: 120px"> <a-select-option v-for="item in options" :key="item.value"> {{ item.label }} </a-select-option> </a-select>
实现搜索功能
为自定义组件添加搜索过滤:
<template>
<div>
<input
v-model="searchQuery"
@input="filterOptions"
placeholder="搜索..."
/>
<ul>
<li
v-for="option in filteredOptions"
@click="selectOption(option)"
>
{{ option.text }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
filteredOptions: this.options
}
},
methods: {
filterOptions() {
this.filteredOptions = this.options.filter(option =>
option.text.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
}
</script>
实现多选功能
扩展基础组件支持多选:

<template>
<div>
<div class="selected-tags">
<span v-for="tag in selectedOptions" @click="removeTag(tag)">
{{ tag.text }}
</span>
</div>
<ul>
<li
v-for="option in options"
@click="toggleSelection(option)"
:class="{ selected: isSelected(option) }"
>
{{ option.text }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
selectedOptions: []
}
},
methods: {
toggleSelection(option) {
const index = this.selectedOptions.findIndex(o => o.value === option.value)
if (index >= 0) {
this.selectedOptions.splice(index, 1)
} else {
this.selectedOptions.push(option)
}
this.$emit('input', this.selectedOptions.map(o => o.value))
},
isSelected(option) {
return this.selectedOptions.some(o => o.value === option.value)
},
removeTag(tag) {
this.toggleSelection(tag)
}
}
}
</script>






