Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get array index from html element?

Hey In my Vue application I have the opportunity to create several persons:

<div v-for="newContent in temp" :key="newContent.id" @click="showId(newContent.id)"  v-show="true">

        <!-- Head of part personal data -->
        <h4 class="person" style="margin-left: 0.95vw">Person 1</h4>

        <!-- Enter Person Data -->
        <testmodul1></testmodul1>      

        <div class="trash">
          <button class="btn btn-outline-danger" @click="deletePerson()">Person löschen</button>
        </div>
        <hr />
</div>

If I want to add more persons, there is a button, which appends more of these person inputs:

<button class="btn btn-outline-secondary" @click="useIt()">Add more persons</button>

useIt(){
  this.temp.push({
    id:this.id+=1
  })
  console.log(this.temp);
},

data() {
return {
  id:0,
  temp:[{
    id:0,
  }]
};

},

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Output of the console.log method in the console (clicked the add button 2 times):

Proxy {0: {…}, 1: {…}, 2: {…}}
[[Handler]]: Object
[[Target]]: Array(2)
0: {id: 0}
1: {id: 0}
length: 2
[[Prototype]]: Array(0)

Now the following problem: Let’s say for example we created 3 new persons. Now I recognize, that the second person is false and I want to delete it. When I click on the of person 2 I want to get the array index of the html element. I have already tried this, but it does not really work well:

<div v-for="newContent in temp" :key="newContent.id" @click="showId(newContent.id)"  v-show="true">

showId(index){
  alert(index);
  }

Is there an other way how I could find out the index in the array of the html div I clicked?

>Solution :

Please, check Vue.js list rendering.

You can iterate through array with both element and index like this:

<li v-for="(item, index) in items">
    {{ index }} - {{ item.message }}
</li>

For your case:

<div v-for="(newContent, index) in temp" :key="newContent.id" @click="showId(index)" v-show="true">
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading