Search code examples
vue.jsvue-resource

Return data from rest api


I'm trying to fetch some data from a rest api. However the result, this.someData, remains undefined.

My component is as follows

<template>
  <div class="list">
    <h1>List</h1>
    <pre>msg: {{msg}}</pre>
  </div>
</template>

<script>
  import Vue from 'vue'
  import VueResource from 'vue-resource'
  Vue.use(VueResource)

  export default {
    name: 'list',
    data () {
      this.$http.get('http://localhost:8080/api/posts/filter?username=tons').then(response => {
      // get body data
        this.someData = response.body
        console.log(this.someData)
      }, response => {
      // error callback
      })

      return {
        msg: this.someData + 'somedata'
      }
    }
  }
</script>

Anyone got a clue about what I'm doing wrong?


Solution

  • 'data' should be just properties. There are 'methods' where you fetch something, and then populate your 'data' properties.

    Correct code looks something like this:

    <script>
        export default {
            data: function() {
                return {
                    someData: null
                }
            },
            methods: {
                getData: function() {
                    // fetch here
                    this.someData = response.body;
                }
            },
            mounted() {
                this.getData(); // or trigger by click or smth else
            }
        }
    </script>
    

    In your template you can then {{ someData }}

    @Bert_Evans is right, you can do some basic calculations in 'data', but they should be syncronous, because of the way reactivity works in Vue.