0

I am using vue2 and I am trying to fetch an api and render the contents in my page, this is all done in my Orgs.vue file and here is the code:

<template lang="html">
  <div class="">
    {{ orgs | json }}
  </div>
</template>

<script>
export default {
  data: {
    orgs: false
  },

  created() {
    request = axios({
      url: 'https://....',
      method: 'GET',
    })
      .then(function(response) {
        this.orgs = response;
      })
      .catch(function(error) {
        console.log('error getting orgs::', error);
      });
  }
};
</script>

<style lang="css">
</style>

However everytime I run the page I get this error:

Property or method "orgs" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. found in Orgs.vue

I tried to change

 data: {
    orgs: false
  },

to

 data() {
    return {orgs: false}
  },

but the error is still there

hidar
  • 5,449
  • 15
  • 46
  • 70
  • Did you try `data: function() { return { orgs: false } }` as in the example at https://vuejs.org/v2/guide/single-file-components.html – harrypujols Aug 16 '17 at 14:38
  • 2
    Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Bert Aug 16 '17 at 15:25

1 Answers1

1

You need save vue instance reference in variable before making request and use it to access vue in response handler. I used vue_instance in example.
And for components init data as function.

data: function() {
    return {
      orgs: false
    }
  },

  created() {
    var vue_instance = this;
    request = axios({
      url: 'https://....',
      method: 'GET',
    })
      .then(function(response) {
        vue_instance.orgs = response.data;
      })
      .catch(function(error) {
        console.log('error getting orgs::', error);
      });
  }

EDIT: In axios response handler this is reference on window. Axios don't know anything about vue.