写一个树形组件的下拉框
时间: 2024-05-13 19:17:00 浏览: 77
layui组件之树形下拉框
5星 · 资源好评率100%
以下是一个简单的树形下拉框组件,使用了递归的方式生成树形结构:
```html
<template>
<div class="tree-dropdown">
<div class="selected" @click="toggleDropdown">{{ selectedText }}</div>
<ul v-show="isDropdownOpen" class="dropdown">
<li v-for="item in items" :key="item.id" :class="{ 'has-children': item.children }">
<div class="item" @click="selectItem(item)">
<span>{{ item.text }}</span>
<span v-if="item.children" class="toggle-icon" @click="toggleChildren(item)">
{{ item.expanded ? '-' : '+' }}
</span>
</div>
<tree-dropdown v-if="item.children" :items="item.children" :selected-id="selectedId" @select="onSelect"></tree-dropdown>
</li>
</ul>
</div>
</template>
<script>
export default {
name: 'TreeDropdown',
props: {
items: {
type: Array,
required: true,
},
selectedId: {
type: Number,
default: -1,
},
},
data() {
return {
isDropdownOpen: false,
};
},
computed: {
selectedItem() {
return this.items.find(item => item.id === this.selectedId);
},
selectedText() {
return this.selectedItem ? this.selectedItem.text : 'Select an item';
},
},
methods: {
toggleDropdown() {
this.isDropdownOpen = !this.isDropdownOpen;
},
selectItem(item) {
this.$emit('select', item.id);
this.isDropdownOpen = false;
},
toggleChildren(item) {
item.expanded = !item.expanded;
},
onSelect(id) {
this.$emit('select', id);
},
},
};
</script>
<style scoped>
.tree-dropdown {
position: relative;
width: 200px;
}
.selected {
border: 1px solid #ccc;
padding: 5px;
cursor: pointer;
}
.dropdown {
position: absolute;
top: 100%;
left: 0;
z-index: 1;
background-color: #fff;
border: 1px solid #ccc;
padding: 5px;
list-style: none;
margin: 0;
}
.item {
display: flex;
align-items: center;
justify-content: space-between;
cursor: pointer;
}
.toggle-icon {
font-weight: bold;
margin-left: 5px;
}
.has-children .toggle-icon:before {
content: '';
display: inline-block;
width: 0;
height: 0;
border-style: solid;
border-width: 4px 0 4px 6px;
border-color: transparent transparent transparent #000;
margin-right: 5px;
}
.has-children.expanded .toggle-icon:before {
transform: rotate(90deg);
}
</style>
```
使用方式:
```html
<tree-dropdown :items="items" :selected-id="selectedItemId" @select="onItemSelect"></tree-dropdown>
```
其中,`items` 是一个数组,用于表示树形结构,每个元素包含 `id`、`text` 和 `children` 字段。`selectedItemId` 表示当前选中的项的 `id`,`onItemSelect` 是选中项后的回调函数。
阅读全文