Access index in v-for when iterating over object

落花浮王杯 提交于 2021-01-29 13:00:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!