5

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 ?

1
  • 3
    What is the error? Commented Jul 21, 2018 at 12:29

1 Answer 1

10
<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)
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

v-for can be used both ways, so i guess that shouldn't be the problem: vuejs.org/v2/guide/…
most linters will complain, In 2.2.0+, when using v-for with a component, a key is now required. vuejs.org/v2/guide/list.html#key
Though the error is most likely getTheSelectedOne not being defined, but who knows till the OP makes contact.
Ah. Missed the part about the key! Yeah. for that use case it is needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.