Skip to content
Advertisement

Can I use the ‘index’ argument in ‘v-for’ nested in a ‘method’?

I need to use index on a v-for but on the same level as the directive itself in order to mutate the state being shown.

<template>
  <div>
    <div v-for="share in sharesPurchased()" :key="share">
      <div>
        <h4>This is some content</h4>
        <p style="border: solid 1px">{{share.count}}</p>
      </div>
    </div>
  </div>
</template>

<script>

  export default {
    data(){
      return {
        shares: [
          {id: 'BMW', count: 1},
          {id: 'Ford', count: 0},
          {id:'Apple', count: 10}
        ]
      }
    },
    methods: {
      sharesPurchased() {
// I want to use this at the v-for level to limit content view
      }
    }
  }
</script>

I want to limit what is being displayed in this iteration so I only show content with a count > 0 i.e: shares[i].count > 0

The result of my intent as per stated above should have <p style="border: solid 1px">{{share.count}}</p> displaying just 1 as only this.shares[0].count is > then 0

Advertisement

Answer

Update: based on your need to use it, this is clearly an X-Y problem. You should be using computed properties instead:

computed: {
    filteredSharesByCount: function() {
        return this.shares.filter(share => share.count > 0);
    }
}

You can then reference it as such in your template:


Outdated answer:

The index is accessible as the second optional argument in the v-for binding:

v-for also supports an optional second argument for the index of the current item.

ie:

<div v-for="(share, idx) in sharesPurchased(shares)" :key="share">

Then, within the loop you can simply use idx if you want a method to have access to the index.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement