用uniapp写一个下拉框
时间: 2023-12-03 08:56:37 浏览: 87
以下是一个简单的下拉框组件的代码示例,使用了uniapp的组件和事件绑定:
template:
```html
<template>
<view class="dropdown">
<view class="dropdown-text" @click="toggleDropdown">{{selectedItem}}</view>
<view class="dropdown-menu" v-show="showDropdown">
<view class="dropdown-item" v-for="(item, index) in items" :key="index" @click="selectItem(item)">
{{item}}
</view>
</view>
</view>
</template>
```
script:
```javascript
<script>
export default {
props: {
items: {
type: Array,
required: true
},
defaultItem: {
type: String,
required: true
}
},
data() {
return {
selectedItem: this.defaultItem,
showDropdown: false
}
},
methods: {
toggleDropdown() {
this.showDropdown = !this.showDropdown;
},
selectItem(item) {
this.selectedItem = item;
this.showDropdown = false;
this.$emit('selected', item);
}
}
}
</script>
```
style:
```css
<style>
.dropdown {
position: relative;
}
.dropdown-text {
cursor: pointer;
padding: 10px;
border: 1px solid gray;
border-radius: 5px;
}
.dropdown-menu {
position: absolute;
top: 100%;
left: 0;
width: 100%;
background-color: white;
border: 1px solid gray;
border-top: none;
border-radius: 0 0 5px 5px;
box-shadow: 0px 2px 2px gray;
z-index: 1;
}
.dropdown-item {
cursor: pointer;
padding: 10px;
transition: background-color 0.2s ease;
}
.dropdown-item:hover {
background-color: #eee;
}
</style>
```
使用方法:
```html
<template>
<view>
<dropdown :items="items" :defaultItem="defaultItem" @selected="onSelect"></dropdown>
</view>
</template>
<script>
import Dropdown from '@/components/Dropdown.vue'
export default {
components: {
Dropdown
},
data() {
return {
items: ['Item 1', 'Item 2', 'Item 3'],
defaultItem: 'Select an item',
selectedItem: ''
}
},
methods: {
onSelect(item) {
this.selectedItem = item;
}
}
}
</script>
```
通过传递`items`和`defaultItem`属性来定义下拉框的选项和默认选项。当用户选择一个选项时,会触发`selected`事件,并将所选项的值传递给父组件。父组件可以通过监听`selected`事件来获取所选项的值,并做相应的处理。
阅读全文