vue实现下拉列表
Vue 实现下拉列表的方法
使用原生 HTML <select> 和 v-model
在 Vue 中可以通过原生 HTML 的 <select> 元素结合 v-model 实现双向数据绑定。

<template>
<select v-model="selectedOption">
<option v-for="option in options" :value="option.value">
{{ option.text }}
</option>
</select>
<p>Selected: {{ selectedOption }}</p>
</template>
<script>
export default {
data() {
return {
selectedOption: '',
options: [
{ text: 'Option 1', value: '1' },
{ text: 'Option 2', value: '2' },
{ text: 'Option 3', value: '3' }
]
}
}
}
</script>
使用第三方 UI 库(如 Element UI)
许多 UI 库提供了更丰富的下拉列表组件,例如 Element UI 的 el-select。

<template>
<el-select v-model="selectedOption" placeholder="请选择">
<el-option
v-for="item in options"
:key="item.value"
:label="item.text"
:value="item.value">
</el-option>
</el-select>
</template>
<script>
export default {
data() {
return {
selectedOption: '',
options: [
{ text: '选项1', value: '1' },
{ text: '选项2', value: '2' },
{ text: '选项3', value: '3' }
]
}
}
}
</script>
自定义下拉列表组件
如果需要完全自定义样式和功能,可以封装一个下拉列表组件。
<template>
<div class="custom-dropdown">
<div class="dropdown-header" @click="toggleDropdown">
{{ selectedOption.text || '请选择' }}
<span class="arrow">{{ isOpen ? '▲' : '▼' }}</span>
</div>
<ul class="dropdown-list" v-show="isOpen">
<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('selected', option.value)
this.isOpen = false
}
}
}
</script>
<style>
.custom-dropdown {
position: relative;
display: inline-block;
}
.dropdown-header {
padding: 8px 16px;
border: 1px solid #ddd;
cursor: pointer;
}
.dropdown-list {
position: absolute;
width: 100%;
border: 1px solid #ddd;
list-style: none;
padding: 0;
margin: 0;
background: white;
}
.dropdown-list li {
padding: 8px 16px;
cursor: pointer;
}
.dropdown-list li:hover {
background: #f5f5f5;
}
</style>
使用 Vue 3 的 Composition API
在 Vue 3 中可以使用 Composition API 实现下拉列表。
<template>
<select v-model="selectedOption">
<option
v-for="option in options"
:key="option.value"
:value="option.value">
{{ option.text }}
</option>
</select>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const selectedOption = ref('')
const options = [
{ text: 'Option 1', value: '1' },
{ text: 'Option 2', value: '2' },
{ text: 'Option 3', value: '3' }
]
return {
selectedOption,
options
}
}
}
</script>
以上方法覆盖了从基础到高级的下拉列表实现方式,可以根据项目需求选择合适的方式。






