Creating toggling elements in Vue.js using dynamic v-show based on index and leveraging falsey v-if

What is the most effective way to use v-show for toggling elements based on their index? I have been able to toggle the elements, but when you click on the element that is already open, it does not close.

<div v-for="(btn, index) in dataArray">
      <button @click="toggle(index)">{{ btn.name }}</button>
      <p v-show="isOpenIndex === index"> {{ btn.desc }} </p>
    </div>

I tried adding a falsey condition to close the currently open element when clicking on another button, but then it doesn't open the clicked element.

<div v-for="(btn, index) in dataArray">
  <button @click="toggle(index)">{{ btn.name }}</button>
  <p v-show="isOpenIndex === index" v-if="isOpen"> {{ btn.desc }} </p>
</div>

Check out this jsFiddle Example

Answer №1

Revision 1: According to @MrNew, the ternary operator within the toggle method suffices:

...
methods: {
    toggle: function(index){
        this.isOpenIndex = ( this.isOpenIndex == index ) ? null : index;
    }
}

Initial response:

Include both conditions in your toggle function: if isOpenIndex is already set, check if it matches the current element's index to deactivate it (returning it to null), otherwise assign it the value of index. If it is not yet defined, then set it to index:

methods: {
    toggle: function(index){
        if( this.isOpenIndex !== null ){
           this.isOpenIndex = ( this.isOpenIndex == index ) ? null : index;
        } else {
           this.isOpenIndex = index;
        }
    }
}

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

Incorporating a JavaScript npm module within a TypeScript webpack application

I am interested in incorporating the cesium-navigation JavaScript package into my project. The package can be installed via npm and node. However, my project utilizes webpack and TypeScript instead of plain JavaScript. Unfortunately, the package is not fou ...

Is Joomla equipped with shortcodes akin to those found in Wordpress?

One of the great features of WordPress is the ability to use shortcodes to insert information into HTML without the need for programming knowledge in PHP or JavaScript. This simplifies tasks and increases safety. For example (this is just a hypothetical s ...

What is the best way to make a trail follow my shapes on canvas?

In my current project, I have implemented a feature where shapes are generated by spinning the mouse wheel. One specific shape in focus is the triangle, but other shapes follow the same generation process. The goal is to create a trail that slowly fades ...

The React error message refuses to disappear even after attempting to refresh the page

Currently, I am immersed in a React project where I have encountered an issue on the Register Page. All errors are being added to a Message component. Interestingly, even after encountering a React error (such as 'Cannot read properties of undefined&a ...

What is the most secure method for conditionally wrapping input with state?

I used to check for errors and wrap the input and error message in a div conditionally. However, I faced an issue where the input would lose focus when re-rendered. Is there a way to wrap the input conditionally without losing focus on re-render if the err ...

Identical HTML elements appearing across multiple DOM pages

My question might seem silly, but I'm facing an issue. I have several HTML pages such as index.html and rooms.html, along with a main.js file containing scripts for all of these pages. The problem arises because I have variables like const HTMLelemen ...

How can I represent non-ASCII characters in Java Script using encoding?

Imagine if ch = á the desired result is = \u00e1 however the current output = %E1 when escape(ch) is used and current output = %C3%A1 when encodeURIComponent(ch) is used I am working with an API that supports Unicode characters. ...

Using Python to interact with forms and click JavaScript buttons

Is there a way to automate form filling on a website by setting specific parameters that will bring up products matching those parameters? I attempted to use mechanize in python, but it does not support javascript. It seems like the process of entering par ...

I need help determining the starting date and ending date of the week based on a given date

I am looking to determine the starting date (Monday) and ending date of a specified date using Javascript. For instance, if my date is 2015-11-20, then the starting date would be 2015-11-16 and the ending date would be 2015-11-21. ...

Storing data from multiple children and triggering a parent component function in Vue: A guide

In my Messaging Tool component, I have several child components that make up the messaging tool interface. You can see the visual representation of these components here: https://i.stack.imgur.com/JoEko.png There are 3 channels within the tool, each openi ...

How to filter out content not contained within a specific form tag using Javascript

One feature of my webpage displays restaurant reviews, each with a like button. However, the issue arises when submitting the like form: everything within and outside of a particular form tag gets sent to the back-end. This makes it challenging to determin ...

Error message "Jquery smooth scrolling issue: Unable to retrieve property 'top' as it is not defined"

I'm currently working on a script for a back to top button that will be placed in the footer of my website. However, I'm running into an issue where I'm getting an error message saying "Cannot read property 'top' of undefined". Any ...

Transforming the JSON data into a text format

I have a JSON object structured like this: { "name": "ok", "country": "US", "phone": "900", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f70745f727e767331707c">[email protected]</a>", ...

What is the process for converting strings or text to EBCDIC using JavaScript?

In the midst of developing a website, I am working on a feature that allows users to input a minimum of 256 characters/strings (with code verification), choose between ASCII or EBCDIC conversion, and view the converted text string displayed on the page bas ...

How can I filter rows in HTML using Vue.js based on string options?

When selecting different options, I want to dynamically add new rows. For instance, if "kfc" is selected, a specific row should be added. If "cemrt" is chosen, another row needs to be included. <div class="card-content" v-for="(bok, index) in rules" :k ...

Adding a class-matched element with a corresponding ID

Despite finding similar questions, I am still unable to achieve the desired outcome. Here is a list: <ul> <li class="class1"></li> <li class="class2"></li> <li class="class3"></li> <li class="class4"&g ...

Is there a method to run code in the parent class right after the child constructor is called in two ES6 Parent-Child classes?

For instance: class Parent { constructor() {} } class Child { constructor() { super(); someChildCode(); } } I need to run some additional code after the execution of someChildCode(). Although I could insert it directly there, the requirement is not to ...

Using React to map through a nested array within an object

In an attempt to extract the nested array "records", my current approach shows the array in the react console, but with an error. I will try to be brief while still providing necessary details. Upon encountering an error, there are 3 lines specifically po ...

What is the best way to send an array to a Vue component?

I am encountering an issue while attempting to pass an array to a Vue component in order to construct a table. The error I am facing indicates that I am passing a string instead of an array. Component: <template> <div> <table> ...

Date selection feature in Material UI causing application malfunction when using defaultValue attribute with Typescript

Recently, I discovered the amazing functionality of the Material UI library and decided to try out their date pickers. Everything seemed fine at first, but now I'm facing an issue that has left me puzzled. Below is a snippet of my code (which closely ...