vue3封装一个Select下拉选择器组件
时间: 2023-07-01 15:17:50 浏览: 85
好的,以下是一个简单的 Vue 3 Select 下拉选择器组件的封装示例:
```vue
<template>
<div class="select-container" @click="toggleDropdown">
<div class="selected-option">{{ selectedOption.label }}</div>
<div class="dropdown" v-show="showDropdown">
<div class="option" v-for="(option, index) in options" :key="index" @click="selectOption(option)">
{{ option.label }}
</div>
</div>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
props: {
options: {
type: Array,
required: true,
},
},
setup(props) {
const selectedOption = ref(props.options[0]); // 初始选中的选项
const showDropdown = ref(false); // 下拉列表是否显示
const toggleDropdown = () => {
showDropdown.value = !showDropdown.value;
};
const selectOption = (option) => {
selectedOption.value = option;
showDropdown.value = false;
};
return {
selectedOption,
showDropdown,
toggleDropdown,
selectOption,
};
},
};
</script>
<style>
.select-container {
position: relative;
width: 200px;
height: 30px;
border: 1px solid #ccc;
border-radius: 4px;
cursor: pointer;
}
.selected-option {
line-height: 30px;
padding-left: 10px;
}
.dropdown {
position: absolute;
top: 100%;
left: 0;
z-index: 10;
width: 100%;
max-height: 200px;
overflow-y: auto;
border: 1px solid #ccc;
border-top: none;
border-radius: 0 0 4px 4px;
background-color: #fff;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
display: none;
}
.dropdown .option {
line-height: 30px;
padding: 0 10px;
cursor: pointer;
}
.dropdown .option:hover {
background-color: #f5f5f5;
}
</style>
```
使用方法:
```vue
<template>
<div>
<select-component :options="options"></select-component>
</div>
</template>
<script>
import SelectComponent from './SelectComponent.vue';
export default {
components: {
SelectComponent,
},
data() {
return {
options: [
{ value: 'option1', label: '选项1' },
{ value: 'option2', label: '选项2' },
{ value: 'option3', label: '选项3' },
],
};
},
};
</script>
```
这个简单的 Select 下拉选择器组件的实现并不完整,你可以根据实际需求进行修改和完善。
阅读全文