使用vue实现一个手风琴
时间: 2024-05-09 12:21:11 浏览: 118
首先,我们需要在Vue中定义一个手风琴组件Accordion,包含多个子组件AccordionItem,每个子组件代表一个手风琴项。
Accordion组件的模板如下:
```
<template>
<div class="accordion">
<slot></slot>
</div>
</template>
```
AccordionItem组件的模板如下:
```
<template>
<div class="accordion-item" :class="{ active: isActive }">
<div class="accordion-item-header" @click="toggle">
<slot name="header"></slot>
</div>
<div class="accordion-item-content" :style="{ height: height + 'px' }">
<slot></slot>
</div>
</div>
</template>
```
其中,isActive表示当前手风琴项是否处于展开状态,height表示手风琴项内容的高度。
Accordion组件和AccordionItem组件的样式如下:
```
<style>
.accordion {
display: flex;
flex-direction: column;
}
.accordion-item {
border: 1px solid #ddd;
margin-bottom: 10px;
}
.accordion-item-header {
padding: 10px;
cursor: pointer;
}
.accordion-item-header:hover {
background-color: #f5f5f5;
}
.active .accordion-item-header {
background-color: #ddd;
}
.accordion-item-content {
overflow: hidden;
transition: height 0.3s ease-in-out;
}
</style>
```
最后,我们需要在AccordionItem组件中实现toggle方法,用于切换手风琴项的展开状态。代码如下:
```
<script>
export default {
data() {
return {
isActive: false,
height: 0
}
},
mounted() {
this.height = this.$el.querySelector('.accordion-item-content').scrollHeight;
},
methods: {
toggle() {
this.isActive = !this.isActive;
}
}
}
</script>
```
完整的Accordion组件代码如下:
```
<template>
<div class="accordion">
<slot></slot>
</div>
</template>
<style>
.accordion {
display: flex;
flex-direction: column;
}
.accordion-item {
border: 1px solid #ddd;
margin-bottom: 10px;
}
.accordion-item-header {
padding: 10px;
cursor: pointer;
}
.accordion-item-header:hover {
background-color: #f5f5f5;
}
.active .accordion-item-header {
background-color: #ddd;
}
.accordion-item-content {
overflow: hidden;
transition: height 0.3s ease-in-out;
}
</style>
<script>
export default {
props: {},
data() {
return {}
},
methods: {},
mounted() {}
}
</script>
<script>
export default {
data() {
return {
isActive: false,
height: 0
}
},
mounted() {
this.height = this.$el.querySelector('.accordion-item-content').scrollHeight;
},
methods: {
toggle() {
this.isActive = !this.isActive;
}
}
}
</script>
<template>
<div class="accordion-item" :class="{ active: isActive }">
<div class="accordion-item-header" @click="toggle">
<slot name="header"></slot>
</div>
<div class="accordion-item-content" :style="{ height: height + 'px' }">
<slot></slot>
</div>
</div>
</template>
```
阅读全文