Search code examples
javascriptvue.jsvue-resource

vue.js http get web api url render list


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


Solution

  • 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)
          })
        })
      }
    })