如何在Vue.js中获取v-for索引?

前端之家收集整理的这篇文章主要介绍了如何在Vue.js中获取v-for索引?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个类似下面的Vue组件:
  1. <div v-for="item in items" :key="there I want get the for-loop index" >
  2.  
  3. </div>
  4.  
  5. ...
  6.  
  7. data(){
  8. items: [{name:'a'},{name:'b'}...]
  9. }

在我的vue.js中执行for循环时如何获取索引?

解决方法

声明一个索引变量:
  1. <div v-for="(item,index) in items" :key="index">
  2.  
  3. </div>

演示:

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

官方文档部分 – Mapping an Array to Elements with v-for(强调我的):

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.

猜你在找的JavaScript相关文章