Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue JS send data from v-for on button click

I'm new to Vue JS, and i'm having a little problem

i'm looping through an array and i have a button inside the div that i'm looping with

the idea is to get the data of the specified data after the click event

for example let's say i have this array numbers: [1,2,3,4,5] and i'm looping through it like this

<div v-for="number in numbers">
    <p>{{ number }}</p>
    <button v-on:click="getTheSelectedOne"> Get The Value </button>
</div>

i tried doing so

<button v-on:click="getTheValueOfTheSelectedOne(number)"> Get The Value </button>

but i got an error,

how can i achieve such a result ?

like image 905
Abdul-Elah JS Avatar asked Jul 21 '18 12:07

Abdul-Elah JS


People also ask

How to use V-on click event in Vue JS?

The v-on:click directive is a Vue.js directive used to add a click event listener to an element. First, we will create a div element with id as app and let’s apply the v-on:click directive to a element. Further, we can execute a function when click even occurs.

What is V-on directive in Vue?

Vue's v-on directive is how you handle events in Vue. The v-on:click directive lets you attach a click event handler to an element. For example, the below Vue app updates every time you click the "Add" button.

How to track each element in vuejs?

We can set Vue to track each element using a key. This would cause it to move elements rather than replacing values. This value should be unique to each element that’s being iterated over.

What is the use of parameters directive in vuejs?

Parameters: This directive accepts function which will be executed when the click event occurs. Example: This example uses VueJS to toggle the visibility of a element with v-on:click. ide.geeksforgeeks.org , generate link and share the link here.


1 Answers

<div v-for="number in numbers">

Should be:

<div v-for="(number, index) in numbers" :key="index">

The following:

<button v-on:click="getTheSelectedOne"> Get The Value </button>

Should be:

<button v-on:click="getTheSelectedOne(number)"> Get The Value </button>

And you must have that method defined:

methods: {
  getTheSelectedOne (number) {
    // then number will be the number
    console.log(number)
  }
}
like image 125
Lawrence Cherone Avatar answered Oct 20 '22 08:10

Lawrence Cherone