VueJS Tutorial: Revealing the Nearest Hidden Element in a List of Items

Is there a way to toggle the visibility of the nearest div element by clicking a button in vue?

Lets imagine I have a collection of items, each containing hidden information.

<ul>
   <li v-for="item in items" :key="item.id">
     <div>
         <p>{{item.text}}</p>
         <button @click="showDetails(item)">Show details</button>
         <div class="details" :class="isVisible ? activeClass : 'hidden'">Some hidden details</div>
     </div>
   </li>
</ul>

Then I implement:

data() {
   return {
      items: [ // list of item objects here]
      isVisible: false,
      activeClass: 'is-visible'
  }
},
methods: {
   showDetails(item) {
       this.isVisible = item;
   }
}

Currently, when I click on a "showDetails" button, all divs with the class .details open and acquire the .is-visible class. However, I only want the closest div related to the item to be shown. It seems like it should be simple, but I can't get it to function properly.

How can I make that happen?

Answer №1

give this a shot

<template>
  <ul>
    <li v-for="(item, index) in items" :key="item.id">
      <div>
        <p>{{item.text}}</p>
        <button @click="displayDetails(index)">Display details</button>
        <div class="details" :class="index == activeIndex ? activeClass : 'hidden'">Some hidden information</div>
      </div>
    </li>
  </ul>
</template>

<script>
export default {
  data() {
    return {
      items: [],
      activeClass: 'is-visible',
      activeIndex: null
    };
  },
  methods: {
    displayDetails(index) {
      this.activeIndex = index;
    }
  }
};
</script>

Answer №2

To enhance readability, consider creating a new component specifically for list items that holds all the necessary logic within itself. Here's an example:

// ListItem.vue
<template>
     <div>
         <p>{{text}}</p>
         <button @click="toggleVisibility">Show details</button>
         <div class="details" v-show="isVisible">Some hidden details</div>
     </div>
</template>

<script>
props: {
    text: String
},
data() {
    return {
      isVisible: false
  }
},
methods: {
  toggleVisibility() {
    this.isVisible = !this.isVisible
  }
}

</script>

Then in your parent component:

<ul>
   <li v-for="item in items" :text="item.text" :key="item.id" is="list-item" /></li>
</ul>




data() {
   return {
      items: [ // include multiple item objects here]
  }
}

Answer №3

Keep track of the visibility status by storing it within the "item"

<ul>
   <li v-for="item in items" :key="item.id">
     <div>
         <p>{{item.text}}</p>
         <button @click="toggleVisibility(item)">Toggle Visibility</div>
         <div class="details" :class="item.isVisible ? activeClass : 'hidden'">Some hidden details</div>
     </div>
   </li>
</ul>




data() {
   return {
      items: [ // list of item objects]
      isVisible: false, 
      activeClass: 'is-visible'
  }
},
methods: {
   toggleVisibility(item) {
       item.isVisible = !item.isVisible;
       this.$forceUpdate();
   }
}

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

The Quasar application does not eliminate console.log() statements during production builds

I've been facing difficulties in removing the console.log() from my Quasar app for production builds. Despite checking solutions on various platforms like StackOverflow, Quasar forums, and GitHub, I am still struggling to eliminate the console.log st ...

Script tags in PHP-Diff are ignored

I am currently utilizing the PHP library at https://github.com/rashid2538/php-htmldiff to compare two HTML pages. However, I am facing an issue where the content inside <script></script> tags is also being compared, which disrupts the functiona ...

Adjust the hue of the three.line when a button in three.js is clicked

Hey there, I'm just starting out with Three.js and I've been having trouble changing the color of a line when a button is clicked. I've created the line using Line Basic Material, but for some reason, the color isn't updating as expecte ...

What is the best way to integrate JavaScript with my HTML command box?

I'm having some trouble with an HTML command box that is supposed to execute commands like changing stylesheets and other tasks. I thought I had everything set up correctly, but it doesn't seem to be working at all. Below is the HTML code with th ...

Utilizing Jquery to locate a link inside a Div and displaying it as specified in the HTML

Looking for a solution to make div elements clickable as links? The usual methods involving window.location or window.open may not be suitable if you have numerous divs with predefined targets. If you're not well-versed in Javascript, finding the righ ...

Mongoose parameters do not accept passing an id or element

When working with MongoDB and using mongoose, I attempted to remove an item from a collection by utilizing the findByIdAndDelete() method. However, I encountered the following error: CastError: Cast to ObjectId failed for value "5f080dd69af4c61774ef447f" a ...

Is it possible for the Jquery Accordion to retract on click?

Hello everyone, I've created an accordion drop-down feature that reveals content when the header of the DIV is clicked. Everything works fine, but I want the drop-down to collapse if the user clicks on the same header. I am new to JQUERY and have trie ...

Ways to adjust the border color when error helper text is displayed on a TextField

I am currently working with React Material UI's TextField element. What I aim to achieve is when the submit button is pressed, the helpertext displayed should be "Please enter the password." It should look like this: https://i.sstatic.net/Nu0ua.png ...

another option besides the nextElementSibling

I have a unique code that applies a style to the following div when another div is clicked, using nextElementSibling. var acc = document.getElementsByClassName("accordion"); var i; for (i = 0; i < acc.length; i++) { acc[i].addEventListener("clic ...

How can I specify to a Vue application that it will be situated in a subdirectory and have the image paths updated accordingly?

I have my Vue app located in a subfolder accessible via the URL: domain.com/myapp/ Within my component template, I currently use: <img :src= "base_path + '/img/undraw_profile.svg'"> where base_path is included in an imported fil ...

Updating state in Vue by utilizing an array of item values

Hello everyone In a simple application, I am attempting to visualize the insertion sort algorithm using Vue. I have successfully written a function that sorts a list of items and returns an array showing each step of the sorting process. The final array i ...

Using VueJS for Dynamic Class Binding

Using Vue version 3.0.5. I have a component named Cube.vue where I am attempting to dynamically assign a blue or green class to a child element. The component has been created and imported into a specific page, however, I am facing issues getting the con ...

Which server or cloud hosting provider is the most ideal for my Laravel and Vue.js 2 application?

I am developing a Laravel 5.5 and Vuejs 2 application tailored for students, which will include various files such as PDFs and tutorials. I am in search of the optimal server or cloud hosting solution for this project. Thank you. ...

Issues arise when implementing Django templates in conjunction with jQuery

Here is an example of a Django template that I am working with: ... <div class="row"> <div class="col-lg-12"> <button type="submit" class="btn btn-primary" id="related"}>KIRK</button> </div> </div> . ...

Is it possible to modify the CSS injected by an Angular Directive?

Is there a way to override the CSS generated by an Angular directive? Take, for instance, when we apply the sort directive to the material data table. This can result in issues like altering the layout of the column header. Attempting to override the CSS ...

The functionality of "#button_1" remains unchanged despite using .click() or .hover() methods

Seems like I made a beginner's error - the #button_1 ID seems to be immune to the jQuery effects of click() or hover(). If someone could spare a moment to check out my JSFiddle, it would be incredibly helpful. It's likely something quite simple ...

Problem with delaying in Jquery's .each method

I'm currently working on a JavaScript project and encountering some issues. Below is my HTML code: <div class="views-row"></div> <div class="views-row"></div> <div class="views-row"></div> <div class="views-row ...

Assign a value to the Angular directive for the SharePoint People Picker

In my create form, I have successfully used a directive to capture and store values in SharePoint via REST. The directive I am using can be found at this link. Within my HTML, I am implementing the directive like this: <sp-people-picker name="CC" id=" ...

Implementing a change event upon setting a value to an input element using JavaScript

My plan is to develop a Chrome extension that can automatically fill passwords. The code for this functionality looks like the following: //get the account document.querySelector("input[type=text]").addEventListener('input', () => { ...

Managing numerous ajax forms within a single page

Upon receiving advice from the following inquiry Multiple forms in a page - loading error messages via ajax, I am endeavoring to incorporate multiple forms within one page. The goal is to insert error messages into the corresponding input div classes. I pr ...