Vue 自定义实现 手风琴模式 的 折叠面板

先看效果

在这里插入图片描述

组件代码



<template>
  <div class="accordion">
    <div
      v-for="(item, index) in items"  :key="index"  class="accordion-item"  
      :class="{ 'is-active': activeIndices.includes(index) }" 
     >
      <div class="accordion-header" @click="toggleItem(index)">
        {{ item.title }}
        <span class="accordion-icon">{{ activeIndices.includes(index) ? '−' : '+' }}</span>
      </div>
      <!-- 这里利用 Array.includes() 方法来判断是否需要展开 -->
      <div class="accordion-content" v-show="activeIndices.includes(index)">
        {{ item.content}}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const props = defineProps({
  // 数据
  data: {
    required:true,
    type: Array,
    default: () => [ ]
  },
  // 是否需要单个展开
  accordion: {
    type: Boolean,
    default:false,
  }
})
// 设置为响应式
const items = ref(props.data)
// 定义一个是否展开数组
const activeIndices = ref([]);

// 将点击的下标传递
const toggleItem = (index) => {
  // 判断展开数组中是否有 当前展开下标 
  const position = activeIndices.value.indexOf(index);
  // 如果有
  if (position > -1) {
    // 使用 splice() 删除,v-show 将不展示
    activeIndices.value.splice(position, 1);
  } else {
  // 如果没有
  	// 判断父组件传递是否需要 单个展开
    if (props.accordion && activeIndices.value.length > 0) { 
      // 如果是,则清空当前数组
      activeIndices.value.splice(0)
    }
    // 将当前点击下标 push 进数组,形成展示
    activeIndices.value.push(index);
  }
};
</script>

// css 自己定义
<style scoped>
.accordion {
  width: 100%;
  max-width: 600px;
  margin: 0 auto;
  font-family: Arial, sans-serif;
}

.accordion-item {
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-bottom: 8px;
  overflow: hidden;
}

.accordion-header {
  padding: 12px 16px;
  background-color: #f5f5f5;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.accordion-header:hover {
  background-color: #e9e9e9;
}

.accordion-icon {
  font-size: 18px;
}

.accordion-content {
  padding: 16px;
  background-color: white;
  border-top: 1px solid #eee;
}

.is-active .accordion-header {
  background-color: #979797;
}
</style>

使用组件


<accordion :data="data" :accordion="true"></accordion>

// 这个主要按照自己的层级导入
import accordion from './accordion.vue'

const data= [
  {title:"标题1",main:"内容1"},
  {title:"标题2",main:"内容2"},
  {title:"标题3",main:"内容3"},
  {title:"标题4",main:"内容4"},
]


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值