Hillcow
Hillcow

Reputation: 969

Vue.js: Save index of v-for?

I would like to save the latest index inside a v-for, but I don't know how to include this logic inside the template?

Basically, I have this:

<div v-for="(reply, index) in replies" :key="reply.id">

I want to include this logic inside the template somehow:

this.last_index = index

I just want to know the amount of total replies in that v-for loop.

Thank you!

Upvotes: 2

Views: 998

Answers (1)

Kamil&#39; Ocean
Kamil&#39; Ocean

Reputation: 616

The most adequate solution is use a computed property in Vue. I usually made it like this:

computed: {
  
  lengthReply() {
  
      return this.replies.length;
      
  }
  
}

If you use Vuex, then you probably can use getters for this case. If you really don't wanna use computed property, then you can put it in your template in curly braces, like this:

{{ replies.length }}

If you need to render only last element in your reply list, then you can use this terrible code:

<div v-for="(reply, index) in replies" v-if="reply === replies[replies.length - 1]">

Upvotes: 1

Related Questions