vue.js http get web api url render list

最后都变了- 提交于 2020-01-01 19:59:33

问题


I am using vue.js to http get from a web api a list of projects and render them in a list but currently the list is only rendering one items of the eight that response is returning in the array, please help! https://codepen.io/mruanova/pen/mprEap?editors=1111

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/0.12.7/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/0.1.13/vue-resource.min.js"></script>
<div id="app">
{{projects}}
<ul>
  <li v-for="project in projects">PROJECT {{project.ProjectId}}</li>
</ul>
</div>
<script>
    new Vue({
        el: '#app',
        data: {
            projects: []
        },
        ready: function () {
            var self = this;
            const url = "https://246gg84zg8.execute-api.us-west-2.amazonaws.com/prod/projects";
            this.$http.get(url).then(function (data) {
                console.log(JSON.parse(data.response).Items.length)
             console.log(JSON.parse(data.response).Items[0].ProjectId)
                self.$set('projects', JSON.parse(data.response).Items)
            })
        }
    })
</script>

current result:

[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

PROJECT

expected:

PROJECT 1 PROJECT 2 PROJECT 3 PROJECT 4 PROJECT 5 PROJECT 6 PROJECT 7 PROJECT 8


回答1:


There are several problems here. First of all, you are using a very old version of Vue, which is inadvisable, to say the least. As soon as I cleaned up the codepen example you posted, pulled in a current version of Vue, and updated things to be more idiomatic, the basic concept of your code works just fine.

https://codepen.io/nickforddesign/pen/rpMLgV?editors=1011

new Vue({
  el: '#app',
  data() {
    return {
      projects: []
    }
  },
  created() {
    const url = 'https://246gg84zg8.execute-api.us-west-2.amazonaws.com/prod/projects';
    this.$http.get(url).then(data => {
      const items = JSON.parse(data.response).Items
      items.map(item => {
        // push to the projects array to make sure Vue's reactivity works
        this.projects.push(item)
      })
    })
  }
})


来源:https://stackoverflow.com/questions/47931508/vue-js-http-get-web-api-url-render-list

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