Guide on toggling all el-collapse-items from the ElementPlus Vue3 Library at once using a single button

Is there a way to expand and collapse all el-collapse-items from the ElementPlus Vue3 Library using just one button in this code snippet?

<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>

Answer №1

Kindly take a look at the code snippet below:

const { ref } = Vue

const app = Vue.createApp({
  setup() {
    const items = ref([{id: 1, title: "first", text: "aaaaaaaaaaaa"}, {id: 2, title: "second", text: "bbbbbbbbbbbb"}, {id: 3, title: "third", text: "ccccccccccc"}])
    const activeName = ref([1]);
    const toggleAll = () => {
      activeName.value = activeName.value.length === items.value.length 
        ? [] 
        : items.value.map(i => i.id)
    }
    return { items, activeName, toggleAll };
  },
})
app.use(ElementPlus);
app.mount('#demo')
<link rel="stylesheet" href="//unpkg.com/element-plus/dist/index.css" />
<script src="//unpkg.com/vue@3"></script>
<script src="//unpkg.com/element-plus"></script>

<div id="demo">
  <div class="flex justify-space-between mb-4 flex-wrap gap-4">
    <el-button type="primary" text bg @click="toggleAll">toggle all</el-button>
  </div>
  <div class="demo-collapse">
    <el-collapse v-model="activeName" accordion>
      <el-collapse-item v-for="item in items" :key="item.id" :title="item.title" :name="item.id">
        <div>
          {{ item.text }}
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
</div>

Answer №2

It is not possible to achieve this while using the accordion mode. According to the documentation:

In accordion mode, only one panel can be expanded at a time

To overcome this limitation, you need to remove the accordion prop and modify the value of activeName to an array, as shown in the documentation:

  const activeNames = ref(['1'])

If you want to expand or collapse all items, you can create a function that updates the activeNames with all the names of the el-collapse-item components or clears it, for example:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Mastering the art of using componentWillUnmount() in ReactJs

According to the official tutorial: componentWillUnmount() is called right before a component is removed and destroyed. It's used for any necessary cleanup tasks like stopping timers, cancelling network requests, or cleaning up DOM elements that we ...

Delaying consecutive calls to query on mouse enter event in React

Currently, I have a React component from antd that utilizes the onMouseEnter prop to make an API query. The issue arises when users hover over the component multiple times in quick succession, which floods the network with unnecessary API calls. To prevent ...

Issue with adding object to array using forEach() function

As I navigate my way through an express route, I am puzzled as to why the "purchasedCards" array turns out empty after going through these database calls. Despite successfully gathering all the necessary information from various DB Queries and placing it i ...

"Encountering a problem with posting API requests using Express

I've encountered a problem where I keep receiving a 404 error when trying to post to a specific route. Here's the code snippet: app.js (code snippet for app.js) .... module.exports = app; api.js (code snippet for api.js) .... module.export ...

Angular page not reflecting show/hide changes from checkbox

When the user clicks on the checkbox, I need to hide certain contents. Below is the code snippet: <input id="IsBlock" class="e-field e-input" type="checkbox" name="IsBlock" style="width: 100%" #check> To hide content based on the checkbo ...

Declaring a sophisticated array as a property within another property in Typescript

As a newcomer to Angular and Typescript, I am facing a challenge while declaring a property with a complex array as one of its values. Here is what I have attempted: groupedItem: { customGroupId: string, cgName: string, category: [{ cu ...

Is there a way to retrieve the width of the parent element in ReactJS from a child component?

The issue has been fixed: I forgot to include .current in my ref... I am trying to determine the width of the element that will hold my component. I came across a solution on SO, but unfortunately it did not work for me as it returned undefined: import R ...

Learn how to configure your Angular uib-typeahead to display suggestions as soon as the model is bound

Currently, I am setting up a search functionality. Whenever a user inputs a character into the search box, I use the ng-change event to call an API, retrieve the model, and bind it to uib-typeahead. My goal is for uib-typehead to immediately start suggesti ...

Unable to execute multiple instances of Selenium PhantomJS concurrently

I have encountered an issue while using Selenium's node.js API to run PhantomJS instances against a series of web pages. The code that I have written to perform actions on the pages is functioning correctly, but it appears that only one instance of Se ...

What are the most effective techniques for utilizing promise.all in your codebase?

When trying to consolidate responses from two API calls in the code below, I'm facing an issue where Promise.all is not being invoked. Any suggestions on what might be implemented incorrectly and the best practice to achieve this using Promise.all? T ...

What is the best way to configure angular $filter to perform case-sensitive string comparisons when filtering data?

I've been working on creating a case-sensitive filter in an Angular controller to filter an array. Here is the data: var stoneArr = [ { "stone_name": "Diamond", "id": 16 }, { "stone_name": "Ruby", "id": 1 ...

Verifying the existing user in a personalized Ajax form that is used to update a Woocommerce order

Currently, I am developing a form that allows users to update specific order details, such as expenses and the reason for the expense. After updating the order, a JavaScript alert confirms the successful update, and the order's metadata is updated acc ...

"Adjusting the height of a div element while considering the

I have 2 elements with different heights and I want to make them equal: var highestEl = $('#secondElement').height(); $('.element').first().height(highestEl); I understand that the second element is always taller than the first one. W ...

Currently, I am compiling a list of tasks that need to be completed, but I am encountering a dilemma that is proving difficult to resolve

Recently delved into the world of Javascript and encountered a roadblock that I can't seem to overcome. Here's the snippet of code causing me trouble: add = document.getElementById("add"); add.addEventListener("click", () => { console.log("Ple ...

Selling beyond webpack's confines

Today I had an interesting thought and couldn't find much information on it, so I decided to share some strange cases and how I personally resolved them (if you have a better solution, please feel free to comment, but in the meantime, this might be he ...

How to update MongoDB documents with referenced objects using Mongoose?

Apologies for any language barriers. I am using node.js + express.js + mongoose.js Here is my schema in mongoose for groups: var groupSchema = new mongoose.Schema({ name: String, users: [{type: mongoose.Schema.ObjectId, ref: 'User'}] ...

What is causing the jQuery selector to only return one element instead of both?

I've encountered a scenario where I am generating a jQuery object from an HTML string and need to target all elements within it with a specific class. What I find interesting is that it returns different results based on the type of selection method ...

Having trouble sending a request in next.js with Docker during the build process?

When utilizing the getStaticProps function to send a request to my backend API from another Docker container, I am encountering an issue. Despite ensuring that the API URL is accurate, the static page fails to be created. This is due to the requirement for ...

The path specified as "react-native/scripts/libraries" does not exist in the file

I've been troubleshooting an error on Github - https://github.com/callstack/react-native-fbads/issues/286. After cloning the repository and running it, I discovered that the error persisted. I am currently updating packages to investigate why this rec ...

I want to retrieve a complete HTML page using an AJAX request

I am trying to retrieve the content of a specific page, but encountering issues when using this function: function getResult() { var url="http://service.semanticproxy.com/processurl/ftfu27m3k66dvc3r43bzfneh/html/http://www.smallbiztechnology.c ...