How to get the v-for index in Vue.js?

前端 未结 4 1616
情歌与酒
情歌与酒 2021-01-07 16:18

I have a Vue component like bellow:

... data(){ items:
相关标签:
4条回答
  • 2021-01-07 16:27

    Updated Answer:: You have indexed array as: "["aaaa","bbbbb"]" then you this script.

    new Vue({
      el: '#app',
      data: {
        items: ["aaaa","bbbbb"]
      }
    })
    <script src="https://unpkg.com/vue"></script>
    
    <div id="app">
      <div v-for="(item, index) in items" :key="index">
        {{ index }} : {{ item }}
      </div>
    </div>

    0 讨论(0)
  • 2021-01-07 16:32

    Declare an index variable:

    <div v-for="(item, index) in items" :key="item.name">
    
    </div>
    

    Demo:

    new Vue({
      el: '#app',
      data: {
        items: [{name: 'a'}, {name: 'b'}]
      }
    })
    <script src="https://unpkg.com/vue"></script>
    
    <div id="app">
      <div v-for="(item, index) in items" :key="item.name">
        {{ index }}: {{ item.name }}
      </div>
    </div>

    Official docs section - Mapping an Array to Elements with v-for (emphasis mine):

    Inside v-for blocks we have full access to parent scope properties. v-for also supports an optional second argument for the index of the current item.

    0 讨论(0)
  • 2021-01-07 16:37

    Create an a method:

      methods: {
        roleCount(key) {
          return key + 1;
        },
      },
    

    If the array keys are are numbered, starting with zero. items[0], items[1], etc..
    you can use the array's keys

    <div v-for="(item, key) in items" :key="key">
    {{ incementIndex(key) }}
    </div>
    

    But if the array keys are typeof String then you can do

    <div v-for="(item, key, index) in items" :key="key">
    {{ incementIndex(index) }}
    </div>
    

    The second version uses the "counter" from v-for loop.

    0 讨论(0)
  • 2021-01-07 16:49

    You can use `$index` to get the index of v-for.

    <div v-for="item in items" :key="`$index`"  >
    
    </div>
    

    and the other method:

    <div v-for="(item, index) in items" :key="index"  >
    
    </div>
    
    0 讨论(0)
提交回复
热议问题