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, }] };
},
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?
Advertisement
Answer
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">