"Deleting an element from an array with a click of a button

Whenever I click on an element in the array, it gets added to the new array at the end

<div class="grid">
  <div class="cell" v-for="item in posts" :key="item">
    <img :class="{active: item.isActive}" :src="item.url" alt width="293px" height="293px" @click="choosePost(item)" />
  </div>
</div>

    choosePost(item) {
    item.isActive = !item.isActive
    if (item.isActive == true) {
      this.selectedPosts.push(item)
    } else this.selectedPosts.splice(????, 1)
  console.log(this.selectedPosts)
},

I am looking to enable removal of an element from the array by clicking on it again. I attempted to use the splice method but struggling with obtaining the index of the selected item. Can you guide me on how to achieve this?

Answer №1

If you want to access the index while using v-for, here is how you can do it:

<div class="grid">
  <div class="cell" v-for="(item, index) in posts" :key="item">
    <img
      :class="{ active: item.isActive }"
      :src="item.url"
      width="293px"
      height="293px"
      @click="choosePost(item, index)"
    />
  </div>
</div>

Answer №2

One way to utilize indexes in a v-for loop is by following this example:

<div class="grid">
  <div class="cell" v-for="(item, index) in posts" :key="item">
    <img :class="{active: item.isActive}" :src="item.url" alt width="293px" height="293px" @click="choosePost(item, index)" />
  </div>
</div>

choosePost(item, index) {
    item.isActive = !item.isActive
    if (item.isActive == true) {
      item["posIndex"] = index;
      this.selectedPosts.push(item)
    } else {
      let pos = this.selectedPosts.map(function(e) { return e.posIndex; }).indexOf(index);
      this.selectedPosts.splice(pos, 1);
    }
  console.log(this.selectedPosts)
},

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 process of updating UseContext global state in React Native and ensuring that the change is reflected across all screens

Struggling with updating global state values using React useContext on different screens? Attempting to change theme color in the App, but changes only appear on the current screen and not carried over to others? Looking for assistance in resolving this ...

Maintaining the state of a React component across page refreshes, with a preference for storing the

As a newcomer to React, I am utilizing localstorage in my React app to store certain data that is needed for page refreshes along with the useEffect() hook. My only concern is that I wish to find a way to conceal this particular data, as it seems I cannot ...

Validating usernames using Jquery's remote method检verifying the username

Struggling with the validation plugin and Laravel 4.2. I've been attempting to use ajax to check the username, but it's not functioning as expected. No matter if the username exists or not, it always appears available. Another problem arises whe ...

Is there a way I can prompt a download based on the API's response?

After successfully calling an API to retrieve the QR Code and displaying it on the DOM based on the user's selection, I am now facing the challenge of downloading it. I attempted the following approach: axios .post(window.URL, body, { responseTyp ...

Exploring Ways to Utilize kendo-window within an Angular Directive

I am facing a challenge with accessing a kendo-window from an Angular Directive. My goal is to pass a message to the window and utilize it as a pop-up, but I haven't been successful in obtaining a handle on it yet. I tried passing it to the directive ...

Using Javascript inside a function along with AJAX incorporated within

Using AJAX in JavaScript within another function http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/dynamic-update/ In this example, instead of generating the first 19 data points with random val ...

Using Javascript to convert numerical input in a text box into its corresponding letter grade

I have been working on this code, but I am facing some issues with displaying the result. My goal is to input a number, such as "75", click a button, and have the bottom textbox show the corresponding letter grade, starting with "C" for 70-80 range. Here i ...

Encountered an issue when trying to establish a connection to the MySQL database on Openshift using a

I am currently running a Node.js app with Express that is deployed on OpenShift. I have set up databases using the PHPMyAdmin 4.0 cartridge. Although I can establish a connection to the database, anytime I run a query, it throws an ECONNREFUSED error. Whe ...

The combination of Array.pop and Array.indexOf is not functioning as expected

I'm having an issue with using Array.pop(Array.indexOf(value)). It seems to always delete the last element in the index, even if the value of that index is not what I intended. Can someone provide some guidance on how to resolve this? CheckBoxHandle ...

Which is better for privacy: underscored prototype properties or encapsulated variables?

There's something that's been on my mind lately - it seems like people are aware of something that I'm not. Let's take a look at an example in FOSS (simplified below)... When creating a class in JavaScript, I personally prefer Crockford ...

Change a JSON Array into an HTML string that is wrapped using an Angular service

Currently, I am attempting to integrate a wysiwyg editor into my Angular application. The objective is to retrieve an array of objects by querying an endpoint, then format the data within each object based on its property name with different HTML tags. Fin ...

Error encountered when attempting to pass more than one value to a function due to syntax

My goal is to call a function, but I am encountering issues with properly escaping values and passing them correctly. The current setup looks like this: function selectdone(sel, title_id, status_type) { ... } $(function() { $("td.status-updates").click ...

retrieve the source URL of the track element from an external source

I have a video URL from openload that includes 2 subtitles in VTT format. <track kind="captions" src="https://thumb.oloadcdn.net/subtitle/aaaaaaaaaaa/J8i5nTIAM3w.vtt" srclang="en" label="English" default /> <track kind="captions" src="https://thu ...

Why You Can Only Use elementByCssSelector Once on TheIntern.io/Selenium

I'm encountering a peculiar problem while running a functional test with Selenium (using the Intern.io framework) where only the first element is being recognized; any subsequent element I try to access throws an error: Error: Error response status: ...

Widget for navigating through Youtube videos

I am currently working on creating a widget that allows users to navigate a YouTube video using buttons. For instance, if the video is of a car race, there would be buttons labeled Lap 1, Lap 2, and so forth. My idea involves adding an extension to the vi ...

Determine the total by multiplying the value of a dropdown menu and a text input field using jQuery when the values are changed

I am new to jQuery and JavaScript. I have a textbox and a select box, and when I enter a value in the textbox and select a value from the select box, I want to display the multiplication of both values in another textbox. I have tried doing this with two t ...

When selecting a link in JavaScript, it automatically deactivates all other links

Hello there! My goal is to deactivate all other links except the one that is clicked. Below is the code I have created so far: JavaScript $(".link-chart").click(function($e) { if($(this).find(".link-selector-two").hasClass('red')) { ...

The browser returns a 404 error for the Web API POST request, but it is successful when made using PostMan and Swagger

I encountered a peculiar issue with my Web API: it returns a 404 error when called from AJAX, but functions perfectly fine on PostMan and Swagger. Here is the post method code snippet: // POST api/<controller> [HttpPost] public int Post(string url, ...

Utilizing Meta Tags to Enable JavaScript Execution within a Chrome Extension

Introducing my latest creation: Frogga, a Chrome Extension that can be accessed from Frogga on GitHub I've been experimenting with different approaches, but I'm only able to access the initial JSON layer. I have the potential to dig deeper, but ...

Develop a reusable method/function within a JavaScript class for future use

I encountered an error message stating React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. I am trying to create a public method within a class so that I ca ...