如何在 Vue.js 中获取 v-for 索引? [英] How to get the v-for index in Vue.js?
本文介绍了如何在 Vue.js 中获取 v-for 索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像下面这样的 Vue 组件:
<div v-for="item in items" :key="我想要获取for循环索引" >
...数据(){项目:[{name:'a'}, {name:'b'}...]}
在我的 vue.js 中执行 for 循环时如何获取索引?
解决方案
声明一个 index
变量:
演示:
new Vue({el: '#app',数据: {项目:[{名称:'a'},{名称:'b'}]}})
<script src="https://unpkg.com/vue"></script><div id="应用程序"><div v-for="(item, index) in items" :key="item.name">{{ 索引 }}:{{ item.name }}
官方文档部分 - 使用 v-for
将数组映射到元素(重点是我的):
在 v-for
块中,我们可以完全访问父作用域属性.v-for
还支持当前项的索引的可选第二个参数.
I have a Vue component like bellow:
<div v-for="item in items" :key="there I want get the for-loop index" >
</div>
...
data(){
items: [{name:'a'}, {name:'b'}...]
}
How can I get the index when I execute the for-loop in my vue.js?
解决方案
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.
这篇关于如何在 Vue.js 中获取 v-for 索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!