javascript - Vue.js 在 v-for 循环中访问嵌套对象

标签 javascript node.js vue.js vuejs2 vue-component

我想访问 Vue.js 中另一个对象数组内的嵌套对象数组的“最新”对象。请参阅下面的示例。

示例对象元素:

[
  {
    'name': 'foo',
    'content': [
      {
        title: 'bar'
      }
    ]
  },
  {
    'name': 'hello world',
    'content': [
      {
        'title': 'this is a test'
      },
      {
        'title': 'this another test'
      }
    ]
  }
]

简化的 vue 代码:

<div v-for="{ element, index } in elements" :key="index">
  <h1>{{ element.name }}</h1>
  <p>Latest content: {{ element.content[element.content.length - 1].title }}</p>
</div>

为什么这不起作用? Vue 说 element.content 未定义

最佳答案

v-for="{ element, index } in elements" 中删除 {} 并将其替换为 ()

Vue.config.devtools = false;
Vue.config.productionTip = false;

new Vue({
  el: '#app',

  data() {
    return {
      elements: [{
          'name': 'foo',
          'content': [{
            title: 'bar'
          }]
        },
        {
          'name': 'hello world',
          'content': [{
              'title': 'this is a test'
            },
            {
              'title': 'this another test'
            }
          ]
        }
      ]
    }
  }
});
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>


<div id="app" class="container">
  <div v-for="( element, index ) in elements" :key="index">
    <h1>{{ element.name }}</h1>
    <p>Latest content: {{ element.content[element.content.length - 1].title }}</p>
  </div>
</div>

关于javascript - Vue.js 在 v-for 循环中访问嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53419186/

相关文章:

javascript - 如何使用node js检查文件中有多少行代码

javascript - 第二次呈现页面后,Jquery 不起作用

vue.js - 在 vue-cli 3 中使用本地字体

javascript - php在POST时显示div元素

javascript - Rest Api 参数验证最佳实践

node.js - Mongoose : moment(). 格式不起作用

node.js - mongodb db.collection.find({}) 没有超过 .limit(101)

vue.js - Vuetify 在 v-autocomplete 上使用附加时无法定位目标

javascript - 我无法将 Autoprefixer 添加到 Express 项目

javascript - ES6 动态 Import() 与 AMD require()