自定义vue下拉框组件
时间: 2023-07-01 20:05:20 浏览: 54
下面是一个简单的自定义 Vue 下拉框组件:
```vue
<template>
<div class="dropdown">
<div class="selected-item" @click="toggleDropdown">{{ selectedItem }}</div>
<ul v-show="isOpen" class="dropdown-list">
<li v-for="(item, index) in items" :key="index" @click="selectItem(item)">
{{ item }}
</li>
</ul>
</div>
</template>
<script>
export default {
props: {
items: {
type: Array,
required: true
},
selectedItem: {
type: String,
default: ''
}
},
data() {
return {
isOpen: false
}
},
methods: {
toggleDropdown() {
this.isOpen = !this.isOpen
},
selectItem(item) {
this.$emit('select', item)
this.isOpen = false
}
}
}
</script>
<style>
.dropdown {
position: relative;
display: inline-block;
}
.dropdown .selected-item {
cursor: pointer;
}
.dropdown .dropdown-list {
position: absolute;
top: 100%;
left: 0;
z-index: 10;
background-color: #fff;
border: 1px solid #ccc;
border-radius: 4px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
padding: 0;
margin: 0;
list-style: none;
}
.dropdown .dropdown-list li {
padding: 8px 12px;
cursor: pointer;
}
.dropdown .dropdown-list li:hover {
background-color: #f5f5f5;
}
</style>
```
这个组件接收一个 `items` 数组和一个 `selectedItem` 字符串作为 props。当用户点击下拉框时,组件会显示一个下拉列表,在列表中选择一个选项后,组件会将选中的选项通过 `select` 事件返回给父组件。
在使用这个组件的时候,可以这样写:
```vue
<template>
<div>
<custom-dropdown :items="items" :selected-item="selectedItem" @select="onSelect"></custom-dropdown>
</div>
</template>
<script>
import CustomDropdown from './CustomDropdown.vue'
export default {
components: {
CustomDropdown
},
data() {
return {
items: ['Option 1', 'Option 2', 'Option 3'],
selectedItem: ''
}
},
methods: {
onSelect(item) {
this.selectedItem = item
}
}
}
</script>
```
这个例子中,我们创建了一个 `CustomDropdown` 组件,并且将一个字符串数组和一个字符串作为 props 传递给它。当用户选择一个选项时,`onSelect` 方法会被调用,将选中的选项保存到 `selectedItem` 变量中。