How can I toggle specific v-if divs within a v-for loop in Vue.js?

I would like to implement a feature where each post in a loop has a dropdown menu that can be shown/hidden when clicked:

<div v-for="(post, index) in posts" :key="index" >
    <div v-on:click.prevent="toggleDropDown(post)">Show/hide menu
    </div>
   <div  v-if="post.showDropDown"> 
      <ul class="menu">         
          <li><a href="#" >Edit</a></li>
          <li><a href="#" >Delete</a></li>
      </ul>
    </div>
    <div>
         {{post.body}}

    </div> 
</div>

Here is the method I am using:

toggleDropDown(post) {
   if (!post.showDropDown) {     
      post.showDropDown =true;   
   } else {       
      post.showDropDown =false;  
   }
  },

However, this implementation is not working as expected. When I click on Show/hide menu, nothing happens.

It should be noted that the data for posts is fetched from the server and the post object does not contain a showDropDown field initially.

If I use v-if="post.showDropDown", all menus open/close together. This behavior is not desired.

How can I correct this issue?

Answer №1

There could potentially be a Vue reactivity issue at play here. One possible solution is to utilize Vue.set

Consider modifying your HTML code to pass the index variable instead of post

<div v-on:click.prevent="toggleDropDown(index)">Show/hide menu
</div>

Then, in your JavaScript:

toggleDropDown(index) {
 if (!this.posts[index].showDropDown) {
    this.$set(this.posts[index], 'showDropDown', true)
 } else {       
    this.$set(this.posts[index], 'showDropDown', false)  
 }
}

If this approach doesn't resolve the issue, you can also try creating a deep copy using JSON.parse(JSON.stringify())

toggleDropDown(index) {
  this.posts[index].showDropDown = !this.posts[index].showDropDown
  this.posts = JSON.parse(JSON.stringify(this.posts))
}

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

Having trouble implementing showLoaderOnConfirm feature in SweetAlert2

I’ve been encountering some difficulties with implementing the showLoaderOnConfirm feature using sweetalert2 and ngSweetAlert for AngularJS. Although the code below runs smoothly and without any errors, I’m not seeing any loading animation. The alert ...

What are the steps for skipping, sorting, and limiting with dynamoose?

After being familiar with MongoDB and mongoose, I am now exploring dynamoose for my app. In order to replicate the below-shown mongoose query using dynamoose, how can I write it? Specifically, I want to achieve the same functionality as the following mong ...

Visualizing network graphs using JavaScript

I am in search of a JavaScript network visualization graph (not a chart) that can handle JSON input effectively. I have tried using the JIT infovis toolkit, RGraph, and space tree to display multiple levels in the graph. However, I have encountered issue ...

Subfolder is not generating the batch file

I need help troubleshooting this code. I created a temporary folder in the C drive, but for some reason the batch file isn't getting created. Can anyone provide some suggestions or insights? var sText, s; var fso = new ActiveXObject("Scripting.Fi ...

Issue encountered while retrieving information from XML file through AJAX

I am facing an issue while using AJAX to fetch data from an external XML file. The error I receive is "Invalid argument" and I am working with IE 8. Below is the code snippet: var xhr; xhr = new XMLHttpRequest(); xhr.open("GET","C:/Users/abc/Desktop/Pr ...

AngularJS' $rootScope is experiencing issues with creating internal variables

My app utilizes $rootScope.requestObj to store key-value pairs representing filters. Throughout the entire application, $rootScope.requestObj is considered a singleton and behaves as expected. However, when I call an external API, I have a service that t ...

Using the on-change event with a textfield can help ensure that the field is cleared if the min-date condition is not met

I recently encountered an issue with an input field that had the type "datetime" and a min-date condition set to today's date. The flow was such that if a valid date was entered, the submit button would be enabled, otherwise it would remain disabled. ...

Creating an installation package for an Electron application on Windows

Is it possible to create a Mac installer for an Electron app using a Windows PC? I have tried running npm make, but it only generates a Windows installer. ...

Ways to compel Capacitor Application to reload through code

Is there a way to programmatically restart my app so that it functions seamlessly across all platforms - electron, iOS, Android, and web? If so, how can I make this happen? ...

The React Component has been displayed on the screen a total of 5 times within the Ionic

While working on my app that includes a dashboard to display data, I noticed in Chrome's console that the render method is being called 5 times. This results in an annoying bouncing effect when the app page is re-rendered. How can I prevent the render ...

The POST method in Node JS request-promises does not properly handle string inputs

When I am trying to establish a connection between my node.js module and another server, I utilize the 'request-promise' library. My implementation for posting data looks like this: rp.({ method: 'POST', headers:{ 'Conte ...

CSS3 Perspective Issue: Solutions for Fixing

I'm currently working on creating a card flip animation that flips in the X axis direction. Right now, the div rotates using the rotateX() method. I attempted to add the perspective property to the upper div, but it ended up distorting my div structur ...

Setting up Laravel with pjax

For the first time, I am experimenting with using pjax in combination with Laravel to enhance page loading speed. Since I am not well-acquainted with this technology yet, I have integrated this package into my project. Everything appears to be functioning ...

Imitate the function of the tab key

Is there a way to replicate the functionality of the tab key to navigate through input fields? <input type="text" @keyup.enter="myfunc"> <input type="text" @keyup.enter="myfunc"> <input type="text" @keyup.enter="myfunc"> new Vue({ met ...

The battle of promises versus async await in Koa middleware

In an attempt to create a Koa middleware, I am faced with the decision of how to proceed based on certain conditions. If the condition is met, I want to move on to the next middleware. If it is not met, I need to stop the flow. Two possible approaches invo ...

The functionality of CKEditor is not compatible with PopUp windows

Currently, I am using CKEditor along with the bPopUp jQuery plugin. When I set up CKEditor in the HTML without any additional scripts, it functions perfectly. However, when I try to embed it into a pop-up window, it stops working correctly. I can see the C ...

Using jQuery to replace the content of a div with a delay?

I am attempting to utilize jQuery to create a fade effect on an element, replace its innerHTML content, and then fade it back in once the new content has been added. I have successfully managed to replace the element's content using the .html() method ...

JQuery AJAX not retrieving data after $.post request

I am currently facing a challenge with a specific JQuery $.post request to a PHP-based processor. To troubleshoot, I set up a test page containing the following code: It's important to note that this is hosted on a subdomain, but there are no cross-d ...

Adding a shadow to a 3D model with Threebox

I am currently working on a project utilizing threebox js and attempting to incorporate shadows for imported 3D models. Following the guidelines outlined in the documentation here. When creating an object, I adjust the property to TRUE (code snippet provid ...

Merge two scripts together

I'm facing an issue with my frontend due to having two separate scripts in my Vue.js component class. How can I merge them into one cohesive script? If the problem stems from elsewhere, what could it be? <script> import GETUSER from "@/graphql/ ...