我有一个类似下面的Vue组件:
- <div v-for="item in items" :key="there I want get the for-loop index" >
- </div>
- ...
- data(){
- items: [{name:'a'},{name:'b'}...]
- }
在我的vue.js中执行for循环时如何获取索引?
解决方法
声明一个索引变量:
- <div v-for="(item,index) in items" :key="index">
- </div>
演示:
- 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="index">
- {{ index }}: {{ item.name }}
- </div>
- </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.