vue实现selectable
Vue 实现可选择的 Select 组件
在 Vue 中实现一个可选择的 Select 组件,可以通过以下几种方式:
使用原生 HTML select 元素
<template>
<select v-model="selectedOption">
<option v-for="option in options" :value="option.value">
{{ option.text }}
</option>
</select>
</template>
<script>
export default {
data() {
return {
selectedOption: '',
options: [
{ text: '选项1', value: '1' },
{ text: '选项2', value: '2' },
{ text: '选项3', value: '3' }
]
}
}
}
</script>
使用第三方 UI 库
Element UI 提供了功能丰富的 Select 组件:
<template>
<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>
</template>
<script>
export default {
data() {
return {
options: [{
value: '选项1',
label: '黄金糕'
}, {
value: '选项2',
label: '双皮奶'
}],
value: ''
}
}
}
</script>
自定义可选择的组件
如果需要完全自定义的选择组件:
<template>
<div class="custom-select">
<div class="selected-option" @click="toggleOptions">
{{ selectedOption || '请选择' }}
</div>
<div class="options" v-show="showOptions">
<div
v-for="option in options"
:key="option.value"
@click="selectOption(option)"
:class="{ selected: option.value === selectedOption }"
>
{{ option.text }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
selectedOption: '',
showOptions: false,
options: [
{ text: '选项1', value: '1' },
{ text: '选项2', value: '2' }
]
}
},
methods: {
toggleOptions() {
this.showOptions = !this.showOptions
},
selectOption(option) {
this.selectedOption = option.value
this.showOptions = false
this.$emit('input', option.value)
}
}
}
</script>
<style>
.custom-select {
position: relative;
width: 200px;
}
.selected-option {
padding: 8px;
border: 1px solid #ddd;
cursor: pointer;
}
.options {
position: absolute;
width: 100%;
border: 1px solid #ddd;
max-height: 200px;
overflow-y: auto;
}
.options div {
padding: 8px;
cursor: pointer;
}
.options div:hover {
background-color: #f5f5f5;
}
.options div.selected {
background-color: #e6f7ff;
}
</style>
实现多选功能
对于需要多选的情况:
<template>
<div>
<div
v-for="option in options"
:key="option.value"
@click="toggleSelection(option)"
:class="{ selected: isSelected(option) }"
>
{{ option.text }}
</div>
<div>已选择: {{ selectedOptions.map(o => o.text).join(', ') }}</div>
</div>
</template>
<script>
export default {
data() {
return {
selectedOptions: [],
options: [
{ text: '选项1', value: '1' },
{ text: '选项2', value: '2' }
]
}
},
methods: {
isSelected(option) {
return this.selectedOptions.some(o => o.value === option.value)
},
toggleSelection(option) {
if (this.isSelected(option)) {
this.selectedOptions = this.selectedOptions.filter(o => o.value !== option.value)
} else {
this.selectedOptions.push(option)
}
}
}
}
</script>
这些方法提供了从简单到复杂的多种实现方式,可以根据项目需求选择合适的方案。







