迭代对象时访问 v-for 中的索引 [英] Access index in v-for when iterating over object

查看:26
本文介绍了迭代对象时访问 v-for 中的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问 Vuev-for绑定.

这是对象:

const obj = {对象 1:{一些数据'},对象 2:{一些数据'},对象3:{一些数据'}}

我正在遍历它:

  • {{ object.some }}
  • 问题是,与循环array相反,index变量在循环object的情况下不保持迭代索引(例如012)但实际上持有对象名称obj1obj2, obj3.

    为什么会这样,在这种情况下我如何才能恢复我宝贵的迭代索引?

    解决方案

    根据 documentation 在迭代对象时,第二个参数是对象键.要访问索引,您应该添加第三个参数,如下例所示:

    {{ 指数 }}.{{名称}}:{{值}}

    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?

    解决方案

    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>
    

    这篇关于迭代对象时访问 v-for 中的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆