【问题标题】:Access nested objects in API using vue resource使用 vue 资源访问 API 中的嵌套对象
【发布时间】:2016-12-04 08:19:48
【问题描述】:

我刚开始使用 vue 资源(以及一般的 ajax),我无法列出嵌套在我的 API 中的数组。

如果这是我的示例 JSON:

{
  "item1" : "data",
  "item2" : 1234,
  "item3" : 5678,
  "item6" : "data",
  "item7" : [ {
    "id" : 0,
    "data2" : "testdata",
    "data3" : "testdata",
  },{
    "id" : 2,
    "data2" : "testdata",
    "data3" : "testdata",
  },{
    "id" : 3,
    "data2" : "testdata",
    "data3" : "testdata",
  } ]
}

我想通过我的 html 中的列表传递 item7 数组,如下所示:

<div id="app">
  <ul v-for="item in items">
      <li>{{ item.data2 }} {{ item.data3 }}</li>
  </ul>
</div>

这是我的 js:

window.onload = function() {

  new Vue({
    el: '#app',
    data: {
      items: {}
    },
    ready: function () {
       this.$http.get('/api/items', function(data) {
        console.log(data);
        this.items = data.item7[];
       });
    },

  });

};

这自然不会返回任何内容,我不确定如何使用 vue 资源通过 this.items = data.item7[]; 循环数组。

【问题讨论】:

    标签: json vue.js vue-resource


    【解决方案1】:

    你只需要写this.items = data.item7,不需要[]

    您还需要将this 绑定到该函数。当您在 HTTP 请求的回调中时,this 指的是别的东西。所以你可以像这样使用.bind(this)

    this.$http.get('/api/items', function(data) {
        this.items = data.item7;
     }.bind(this));
    

    最后,如果items 是一个数组,你应该将它实例化为一个数组:

    data: {
      items: []
    },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-16
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      相关资源
      最近更新 更多