I
I
Ilya Kunovskiy2021-03-26 11:58:01
Vue.js
Ilya Kunovskiy, 2021-03-26 11:58:01

How to bind a click inside a component inserted via v-for?

There are 5 components exposed through v-for, there is a button inside the components, I need that when this button is clicked, the index of this button is assigned to the variable.
The problem is that the component is exposed through v-for, and not the button itself and I I don't understand how to assign an index to a button
Sample code:
App.vue:

<eclipse-item v-for="i in 5" :key="i" ></eclipse-item>

Component:
<template>
  <div class="circle__area">
   <span class="circle__text" :class="'circle__text' + circleNumber">{{circleText[circleNumber]}}</span>
   <button class="circle__button">
    <img class="circleImage" :class="'circleImage' + circleNumber" :src="require('@/assets/img/eclipse' + circleNumber + '.png')">
   </button>
  </div>
</template>

Thank you in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Anton, 2021-03-26
@Fragster

In the component, pass the index through the prop, when you click on the button, emit this index in the event. In the parent component - catch. something like this: https://jsfiddle.net/y5981mwc/

W
WapSter, 2021-03-26
@wapster92

  1. In eclipse-item, pass props with its index, and pass that index to the event method that should be hung on the button.
  2. In eclipse-item you can create a slot for the button and insert the button directly into the parent component
    <eclipse-item v-for="i in 5" :key="i" ><button @click="myMethod(i)">Что-то там</button></eclipse-item>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question