属性或方法“orgs”未在实例上定义,但已引用

时间:2017-08-16 14:06:27

标签: javascript vue.js vuejs2

我正在使用vue2,我正在尝试获取api并在我的页面中呈现内容,这都在我的Orgs.vue文件中完成,这里是代码:

<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>

但每次我运行页面时都会收到此错误:

  

属性或方法“orgs”未在实例上定义,但在呈现期间引用。确保在数据选项中声明反应数据属性。在Orgs.vue中找到

我试图改变

 data: {
    orgs: false
  },

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

但错误仍然存​​在

1 个答案:

答案 0 :(得分:1)

在发出请求之前,您需要在变量中保存vue实例引用,并使用它来访问响应处理程序中的vue。我在示例中使用了vue_instance 对于组件init data作为函数。

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

编辑:在axios响应处理程序this中引用window。 Axios对vue一无所知。