Search code examples
javascriptvue.jsvuejs3element-plus

How to toggle all el-collapse-items of ElementPlus Vue3 Library with a single button?


Using this code, how to expand and collapse.. toggle all el-collapse-items of ElementPlus Vue3 Library with a single button ?

<template>
<div class="demo-collapse">
<el-collapse v-model="activeName" accordion>
  <el-collapse-item title="Consistency" name="1">

<script lang="ts" setup>
import { ref } from 'vue'

const activeName = ref('1')
</script>

https://element-plus.org/en-US/component/collapse.html#accordion


Solution

  • You can not do this in the accordion mode. As documentations says:

    In accordion mode, only one panel can be expanded at once

    To do this, you have to remove the accordion prop and change the activeName value to an array, just like in the documentation:

      const activeNames = ref(['1'])
    

    To expand/collapse all items you can create a function that will change the value of activeNames to contain all the names of el-collapse-item components or to be empty, e.g

    toggleElements() {
      if(activeName.value.length) {
        activeName.value = [];
      } else {
        activeName.value = ['1', '2', '3', ...];
      }
    }