你能写用vue实现下拉框的代码吗
时间: 2023-06-25 12:05:18 浏览: 128
当然可以,下面是一个简单的Vue下拉框组件代码:
```html
<template>
<div class="select-wrapper">
<div class="select" :class="{active: isOpen}" @click="toggle">
<div class="selected-option">{{ selectedOption }}</div>
<i class="fas fa-chevron-down"></i>
</div>
<ul class="options" v-show="isOpen">
<li v-for="(option, index) in options" :key="index" @click="select(option)">
{{ option }}
</li>
</ul>
</div>
</template>
<script>
export default {
props: {
options: {
type: Array,
required: true
},
defaultOption: {
type: String,
default: ''
}
},
data() {
return {
isOpen: false,
selectedOption: this.defaultOption
}
},
methods: {
toggle() {
this.isOpen = !this.isOpen
},
select(option) {
this.selectedOption = option
this.isOpen = false
}
}
}
</script>
<style>
.select-wrapper {
position: relative;
display: inline-block;
}
.select {
border: 1px solid gray;
padding: 10px;
display: flex;
align-items: center;
cursor: pointer;
}
.select.active {
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
}
.selected-option {
flex: 1;
}
.options {
position: absolute;
top: 100%;
left: 0;
border: 1px solid gray;
border-top: none;
list-style: none;
padding: 0;
margin: 0;
background-color: white;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
max-height: 200px;
overflow-y: auto;
}
.options li {
padding: 10px;
cursor: pointer;
}
.options li:hover {
background-color: #f1f1f1;
}
</style>
```
使用方法:
```html
<template>
<div>
<my-select :options="colors" default-option="Select a color"></my-select>
</div>
</template>
<script>
import MySelect from './MySelect.vue'
export default {
components: {
MySelect
},
data() {
return {
colors: ['Red', 'Blue', 'Green', 'Yellow']
}
}
}
</script>
```
这个组件会渲染一个类似下拉框的UI,其中`options`是下拉框中的选项,`defaultOption`是默认选项。当用户点击下拉框时,会显示下拉框的选项列表,用户可以选择其中的一个选项。选择完成后,下拉框会显示所选的选项。
阅读全文