【问题标题】:For loop of objects对象循环
【发布时间】:2019-01-07 16:05:54
【问题描述】:

我正在尝试对一组对象进行 for 循环,但由于它们的名称不同,所以我被卡住了。

<div id="components-demo">
    <div>Travel Information</div>
    <ul>
        <li 
          v-for="(todo, index) in todos"
          v-bind:id="index"
          v-bind:title="todo"
            >{{todo}}</li>
    </ul>
</div>


var newData = @Html.Raw(Json.Encode(Model));
// Object returns like { Passenger: "Tom Jones", Airline: "United Airways", Destination: "Atlanta, GA", etc. }    

var vm = new Vue({
    el: '#components-demo',
    data: {
        todos: [
            { newData }
        ]
    }
})

在 Vue 的开发者工具中,它列出了如下的对象:

todos: Array [1]
   0: Object
     Passenger: "Tom Jones"
     Airline: "United Airways"
     Destination: "Atlanta, GA"
     etc.

最后,我希望列出包含这些项目的 li,但似乎无法循环遍历,除非我准确指定每个项目。

【问题讨论】:

  • “他们的名字都不一样” 你的意思是他们有不同的钥匙?我怀疑您还需要第二个循环来迭代对象键。
  • 好吧,既然他们不都叫Passenger,我不能做newData.Passenger perse

标签: vue.js vuejs2


【解决方案1】:

根据你说的对象构造。

<div id="components-demo">
    <div>Travel Information</div>
    <ul>
        <li v-for="(item, index) in todos" :key="index">{{ item.Passenger }}</li>
    </ul>
</div>

使用嵌套循环列出动态对象:

<div id="components-demo">
    <div>Travel Information</div>
    <ul>
        <li v-for="(item, index) in todos" :key="index">
          <ul>
             <li v-for="(value, key) in item" :key="key">{{ key }} : {{ value }}</li>
          </ul>
        </li>
    </ul>
</div>

【讨论】:

  • 这很有效,谢谢。我看到我需要添加项目、索引而不是使用对象本身
【解决方案2】:

您正在将对象分配给数组,您可以直接循环遍历对象https://jsfiddle.net/cckLd9te/4656/

data: {
    todos: newData 
  },

【讨论】:

    猜你喜欢
    • 2016-02-21
    • 2020-06-05
    • 2017-09-20
    • 2017-01-25
    • 2013-06-23
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多