如何使用Vue JS为嵌套数组设置增量计数器 [英] How to set incremental counter for nested arrays using Vue JS
问题描述
我在使用Vue JS的数组中有两个级别,我需要一个从0开始的索引,并且对顶部数组中的每个项目递增。
I'm two levels deep in arrays using Vue JS and I need an index that starts at 0 and increments for each item in the top array.
我的HTML:
<div v-for="member in cast"> <!--array #1-->
<input name="cast_list[@{{ memberCounter }}][actor]" value="@{{ member.actor }}">
<input name="cast_list[@{{ memberCounter }}][role]" value="@{{ member.role }}">
<div v-for="group in ensemble_groups"> <!--array #2-->
<input type="checkbox"
name="cast_list[@{{ memberCounter }}][groups][]"
value="@{{ group }}"
v-model="member.groups"
id="g-@{{ memberCounter }}-@{{ $index }}">
<label for="g-@{{ memberCounter }}-@{{ $index }}">@{{ group }}</label>
</div>
</div>
和我的Vue JS:
data: {
ensemble_groups: [{{ ensemble_groups }}"{{ group_name }}",{{ /ensemble_groups }}],
cast: [
{{ cast_list }}
{
actor: '{{ actor }}',
role: '{{ role }}',
groups: [{{ groups }}"{{ value }}",{{ /groups }}],
counter: 0 // trying to set default value
},
{{ /cast_list }}
],
},
computed: {
memberCounter: function() {
return this.counter++;
},
},
计算属性作为我的计数器,但它不是我的行为,如何我需要它。 @ {{$ index}}
将工作除了在我的第二个数组,它被循环为 0,1,2,3
You can see I'm trying to define a computed property as my counter, but it's not behaving how I need it. @{{ $index }}
would work except within my 2nd array it gets looped as 0,1,2,3
over and over instead of holding fast to the incremental value of my first array.
推荐答案
您可以为每个索引指定一个别名像这样:
You can specify an alias for each index like this:
<div v-for="(firstIndex, member) in cast"> <!--array #1-->
所以,在你的第二个循环中,你可以调用 firstIndex
So, inside your second loop you can call the firstIndex
如果您使用Vue 2.0,您必须逆转索引的顺序:
If you're using Vue 2.0, you have to reverse the order of the index:
<div v-for="(member, firstIndex) in cast"> <!--array #1-->
这篇关于如何使用Vue JS为嵌套数组设置增量计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!