问题
I am trying to access the index of an iteration in Vue's v-for binding.
This is the object:
const obj = {
obj1: {
some: 'data'
},
obj2: {
some: 'data'
},
obj3: {
some: 'data'
}
}
and I'm looping over it:
<li v-for="(object, index) in obj" :key="index">{{ object.some }}</li>
The problem is that contrary to looping over an array the index variable in case of looping over an object like this does not hold the iteration index (e.g. 0, 1, 2) but actually holds the object name obj1, obj2, obj3.
Why is it behaving like that and how can I get my precious iteration index back in this case?
回答1:
According to the documentation when iterating over an object the second parameter is the object key. To access the index you should add a third parameter as in the following example:
<div v-for="(value, name, index) in object">
{{ index }}. {{ name }}: {{ value }}
</div>
回答2:
The documentation says:
When iterating over an object, the order is based on the enumeration order of
Object.keys(), which is not guaranteed to be consistent across JavaScript engine implementations.
So this is not really a good idea.
来源:https://stackoverflow.com/questions/57589420/access-index-in-v-for-when-iterating-over-object