Utilizing Vue's click event functionality with arrays

<div v-for="(n, index) in items" :id="n" @click="myMethod($event)">{{n}}</div>

The array contains various animals such as mouse, bull, tiger, rabbit, pig, cat, dog, and horse.

In the method below, we are logging the id of the clicked element:
myMethod: function(event){
    console.log(event.target.id);
}

While binding the content to the id of each div helps identify which item was clicked, accessing the index of the items within myMethod() is proving challenging. However, there’s a need to utilize the index for additional tasks. How can this issue be resolved?

Answer №1

Is there a way to utilize the index of each item for additional purposes?

To access the index, simply pass it like this:

<div v-for="(n, index) in items" :id="n" @click="myMethod(index)">{{n}}</div>

You can see a working example on CodeSandbox: https://codesandbox.io/s/m363rl73oy

Here's another demonstration:

var app = new Vue({
  el: '#app',
  data: {
    items: ['mouse', 'bull', 'tiger', 'rabbit', 'pig', 'cat', 'dog', 'horse']
  },
  methods: {
    handleClick: function(index) {
      alert(index)
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed9b9888addfc3d8c3dcda">[email protected]</a>/dist/vue.js"></script>
<div id="app">
  <div @click="handleClick(index)" v-for="(item, index) in items" :key="index">{{item}}</div>
</div>

If you need to pass data to the method, you can do so by passing it as shown below:

var app = new Vue({
  el: '#app',
  data: {
    items: ['mouse', 'bull', 'tiger', 'rabbit', 'pig', 'cat', 'dog', 'horse']
  },
  methods: {
    handleClick: function(item) {
      alert(item)
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f98f8c9cb9cbd7ccd7c8ce">[email protected]</a>/dist/vue.js"></script>
<div id="app">
  <div @click="handleClick(item)" v-for="(item, index) in items" :key="index">{{item}}</div>
</div>

Answer №2

To include the index in the method, you can use this syntax.

<div v-for="(item, idx) in itemList" :key="item.id" @click="handleClickEvent($event, idx)">{{ item.name }}</div>

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 with adding text to circles in D3 on a line?

I have successfully created some line charts on d3 and then added circles to every 3rd element of the line. Now I am attempting to add text to those circles as well. // defining a circle variable var circles=g2 .append("g") .attr("i ...

Steps to displaying a genuine Docx file within a Material CardMedia

Currently, I am facing an issue with positioning a docx file in my app. Interestingly, jpg and mp4 files are displaying correctly, but the docx file is not positioned as expected. If you want to try it out, simply open a doxc file. In the FileContentRend ...

Is it possible that jest is unable to catch the exception?

I have a simple function that looks like this: function foo({ platform }) { if (platform === 'all') { throw new Error('Platform value can only be android or ios'); } return `${platform}`; } After writing unit tests, the re ...

What is the best way to add an element conditionally within a specific Vue Component scope?

I've been working on creating a Component for titles that are editable when double-clicked. The Component takes the specific h-tag and title as props, generating a regular h-tag that transforms into an input field upon double click. It's function ...

Resetting component state in React Native is essential for maintaining the correct

I need to reset the state of specific states without affecting others. When a button is clicked, the values of present_count, total_count, present, and total should all be restored to their original state (0), while keeping the state of subjects and text u ...

Should we bundle everything into one script with webpack, considering Npm and Dev dependency or just dependencies?

Imagine a scenario where we use webpack to bundle all our code into a single JS file, which automatically imports dependencies. In this case, is it necessary to include any dependencies in the package.json, or can they all be listed as --save-dev? Let&apo ...

What is the best way to deploy a nodejs expressjs application to a server?

I have successfully developed a nodejs and express application that works perfectly on my localhost. To start the application, I simply run the command npm start or node index.js. Recently, I uploaded all the necessary files, including node_modules, to a ...

Vue: Storing selected list values in an array

I am working on a Vue application where I need to select two elements from a list component and place them inside an array. Currently, I have my list set up with selection functionality thanks to Vuetify. I have bound the selected items to an array using v ...

Steps for retrieving user timezone offset and transmitting it to the server in an ASP.net application

I need assistance with capturing and sending a user's timezone or offset when they successfully sign in. I came across the "getTimezoneOffset" method in JavaScript, but I'm unsure how to automatically send this data without the user explicitly in ...

Learn how to dynamically disable a button based on the input state matching an email pattern!

I'm facing an issue with my login form that has 2 input fields and a login button. One of the input fields requires a valid email pattern. If any of the input fields are left empty, the login button becomes disabled. However, when an incorrect email p ...

Determining Existence Before Adding in Node.js and Sequelize: Handling Asynchronous Challenges

Having recently delved into the world of node.js, I find myself grappling with the intricacies of synchronous and asynchronous execution in this environment. My current setup involves working with node, sequelize using sqlite, and async.js. Within this f ...

Troubleshooting Angular 2 with TypeScript: Issue with view not refreshing after variable is updated in response handler

I encountered a problem in my Angular 2 project using TypeScript that I could use some help with. I am making a request to an API and receiving a token successfully. In my response handler, I am checking for errors and displaying them to the user. Oddly en ...

Ensure that cookies intended for cross-site contexts are marked as Secure to enable their setting across different sites

When using nookies in Next.js on browsers with Chromium, an error is occurring as mentioned in the title and the cookie is not being saved properly. The website is securely hosted with SSL/HTTPS. Have already attempted: - sameSite = None - secure = tru ...

Setting up Okta authentication with the Composition API in a Vue application

Currently, I am in the process of setting up a Vue authentication application with Okta. The foundation of this project is based on the code repository found at https://github.com/okta/okta-vue. My main objective is to migrate the routing and sign-in redir ...

Guide to implementing Vuetify tabs alongside Vue Router

I have a scenario with two Vuetify tabs in this jsfiddle, but the documentation lacks examples of using vue-router with them. After stumbling upon a helpful Medium.com post about integrating Vuetify with vue-router, I came across the following code: <d ...

Fixing a compilation error when attempting to paste text into a file with Selenium Webdriver

I am new to using Selenium webdrivers and encountering a compilation error with the code below. Can anyone provide some assistance? My goal is to save a message into a file rather than displaying it on the console. testResultFile="C:\&b ...

Issue with loading glb file in three.js: The 'format' property is not compatible with this material

When loading a .glb file I created in Blender using three.js, I am encountering an error message three.module.js:7950 THREE.MeshStandardMaterial: 'format' is not a property of this material.. The rest of the content loads correctly. What does thi ...

Clicking on the current component should trigger the removal of CSS classes on its sibling components in React/JSX

Currently, I am working on creating a navigation bar using React. This navigation bar consists of multiple navigation items. The requirement is that when a user clicks on a particular navigation item, the class 'active' should be applied to that ...

An Ajax call nested within another Ajax call

I've implemented an AJAX request to load my "home" page and "about" page into a designated "container" when a menu link button is clicked on my index.php. Now, I have three links on my "home" page and I want each of these links to open within the same ...

How do I retrieve the class of an element nested within another element using jQuery?

If we consider a scenario where there is a table named unitTables with various rows, each containing the selected class that we want to retrieve for a variable. This specific table is just one of many similar tables on the webpage. Since other tables also ...