Is it possible to apply v-model to a function that toggles a particular accordion panel?

I am curious about a possibility in my specific situation. I have two Vue/Element UI accordions on a page and I've created an "open all, close all" button for them. How can I assign a unique ID to each accordion and then pass that ID to the function that toggles the accordions? Alternatively, is there a way to use the same v-model with a different unique identifier so I can apply the function to each accordion individually when opening or closing all items within that particular accordion section.

https://codepen.io/mDDDD/pen/gOwxQxz

html:

<div id="app">
<template>
  <div class="toggle-block">
     <button @click="togglePanels()" class="toggle">
            {{ activeNames.length === 4 ? "Close" : "Open" }} all
          </button>
    </div>
<el-collapse v-model="activeNames">
    <el-collapse-item title="Panel 1" name="1">
        <div class="collapse-content">
            <p>Content 1</p>
        </div>
    </el-collapse-item>
    <el-collapse-item title="Panel 2" name="2">
        <div class="collapse-content">
            <p>Content 2</p>
        </div>
    </el-collapse-item>
    <el-collapse-item title="Panel 3" name="3">
        <div class="collapse-content">
            <p>Content 3</p>
        </div>
    </el-collapse-item>
    <el-collapse-item title="Panel 4" name="4">
        <div class="collapse-content">
            <p>content 4</p>
        </div>
    </el-collapse-item>
</el-collapse>

  <div class="spacer"></div>
  
  
    <div class="toggle-block">
     <button @click="togglePanels()" class="toggle">
            {{ activeNames.length === 4 ? "Close" : "Open" }} all
          </button>
    </div>

<el-collapse v-model="activeNames">
    <el-collapse-item title="Panel 1" name="1">
        <div class="collapse-content">
            <p>Content 1</p>
        </div>
    </el-collapse-item>
    <el-collapse-item title="Panel 2" name="2">
        <div class="collapse-content">
            <p>Content 2</p>
        </div>
    </el-collapse-item>
    <el-collapse-item title="Panel 3" name="3">
        <div class="collapse-content">
            <p>Content 3</p>
        </div>
    </el-collapse-item>
    <el-collapse-item title="panel 4" name="4">
        <div class="collapse-content">
            <p>content 4</p>
        </div>
    </el-collapse-item>
</el-collapse>
  </template>
</div>

js:

var Collapse = {
      data() {
        return {
         activeNames: []
        }
      },
  methods: {
    togglePanels: function() {
      if (this.activeNames.length <= 3) {
        this.activeNames.push("1", "2", "3", "4");
      } else if ((this.activeNames.length = 4)) {
        this.activeNames = [];
      }
    }
  }
    }
var col = Vue.extend(Collapse)
new col().$mount('#app')

Answer №1

One effective approach is to encapsulate a single accordion within its own component. This way, each accordion can manage its state independently and you can incorporate multiple accordions without any conflicts.

Check out an example here: https://codepen.io/andrei-gheorghiu/pen/QWKqbwv

data: () => ({
  accordions: 2
})

<accordion v-for="(accordion, key) in accordions" :key="key" />

I've also added the option to pass in the number of panels as a prop, allowing flexibility in the number of panels that can be opened or closed. Now, you are not limited to just 4 panels but can have as many as needed.

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

Using CSS3 or Javascript to create smooth page transition animations

I am interested in recreating the transition page on the website using JavaScript or CSS3, as shown in the work section. However, I am unsure of how to achieve the same result. Can you provide any guidance or ideas on how to accomplish this? Thank you fo ...

When using videojs, I have the ability to include a Text Track event handler, however, there is currently no option to remove it

I implemented a listener for the 'cuechange' event on a Text Track and it's functioning correctly. However, I am unable to figure out how to remove this listener. I have attempted the instructions below to remove the listener, but it continu ...

The performance of Google Maps API is compromised by a high number of markers,

Currently, I am facing a challenge with loading approximately 600 Google Map markers on page load using the addMarker function. The loading time for the page is quite long. Is there any way to optimize the loading speed while still utilizing the addMarke ...

Vuetify chip displaying lengthy text

Is there a workaround for the issue of the text being cut in the Vuetify component v-chip when it is too long? new Vue({ el: '#app', vuetify: new Vuetify(), data() { return { } }, }) <link href="https://cdn.jsdel ...

Obtaining access to a class variable within a setTimeout function

I am working on a JavaScript class that needs to publish events at regular intervals. The current code I have is as follows: class TimerService { constructor(BroadcastService) { this.Broadcast = BroadcastService; this.timeout; this.warningTi ...

Classroom overflowing with logical thinking

I have successfully created a code that functions as intended. <tr v-for="(day, index) in days" :key="index" :class="[ { no_target: day.date.format('dddd') == 'Sunday&apos ...

How to shuffle the elements of an array saved in a JSON file using discord.js

I've been working on a Discord bot as a way to learn more about Javascript. While creating a command that pulls random quotes from an array stored in a separate JSON file, I encountered an issue that has me stumped. var config = require("./settings.j ...

Adjust the transparency of the other tab as I hover over the current tab

My latest project involves creating a dropdown menu. I want to make it so that when I hover over a tab, the opacity of the other tabs in the menu changes, except for the current tab. For example, when I hover over the Home Tab, the state of the Home tab a ...

Looping through a JSON object to create a table showcasing public holidays

Currently, I am working on creating a table that lists all the public holidays. The table comprises rows with holiday names on the left and dates on the right. Unfortunately, the table only displays data from the final array of the JSON object, whereas I ...

Stacking sheets of hole-punched paper on top of one another, create a visually captivating

I am in search of a way to create those distinctive black dots with papers displayed here: body { background: linear-gradient(#ccc, #fff); font: 14px sans-serif; padding: 20px; } .letter { background: #fff; box-shadow: 0 0 10px rgba ...

Can you come up with a catchy one-liner for an array that contains all the elements of the arrays that came

I am currently working with the array [1,2,3,4,5,6,7,8,9] My goal is to achieve [ [1], [1,2], [1,2,3], [1,2,3,4], [1,2,3,4,5], ... ] I envision the desired outcome as const var = array.reduce **using some form of black magic** I ...

Implementing VueJs Vuetify Autocomplete feature with clickable hyperlinks

I am working with Vuetify and I want to create an autocomplete feature similar to the one on their official site. However, I am encountering some issues: The items value is not appearing in the return list and I am unsure how to display the links. Here i ...

Integrating Dynamics CRM with an External Source to Trigger Workflows

Scenario: Imagine a scenario where you want to trigger an existing workflow or a custom action from a webpage located outside the CRM Dynamics environment, such as MS CRM 2011-2013-2015-2016 and 365. Potential Solution: One possible solution could be to ...

Javascript encountering compatibility issues with certain versions of Internet Explorer; employing browser detection workaround

Unfortunately, Internet Explorer is causing issues when trying to execute this script (specifically the 'else' part). Despite numerous attempts, I have been unable to resolve it. $(document).ready(function(){ if (navigator.appName != "Micros ...

Utilizing JS Underscore for combining and organizing arrays with common keys

I am facing a scenario where I have two arrays: "array_one": [ { "id": 1, "name": One }, { "id": 2, "name": Two } ] "array_two": [ { "id": 1, "name": Uno }, { "id": 3, "name": Three ...

Use React Router to create a link that goes to the same URL but passes along unique state

Can someone help me figure out how to open the same URL using react-router Link while passing different state each time? <Link to={items.vehicleModelId === 2 ? '/ecgo-3' : items.vehicleModelId === 3 && '/ecgo-5' ...

What is the best way to retrieve the Firebase API key from an Express backend in order to initialize firebase.initializeApp()?

At the moment, my Firebase.js file is structured to fetch the API key from the .env file on the client side. Here's a snippet of the code: import firebase from "firebase/compat/app"; import "firebase/compat/auth"; import "firebase/compat/firestore" ...

Adjust the color according to the chosen route in a Vue component

I am looking to dynamically change the CSS color based on the route or a prop for a route. For example, if I navigate to the home page, I want the header to be red. If I visit the about page, I want the header to be green. I have attempted this using rout ...

Find the variance between the initial time and the present time, as well as the final time and the current time

If a user logs in before the start time of a game, they will receive a message indicating that the game will start in 01h:10m:23s. If the user logs in after the start time but before the end time, they will see a message stating that the game closes in 0 ...

Guidelines for setting up a universal Handler using React and AXIOS

In my current project, I am utilizing ReactJs and AXIOS. My goal is to implement a global error handler without having to add a catch statement to each request throughout the codebase. To achieve this, I have created a service that consolidates all request ...