使用Axios和Vue获取api数据 - 返回undefined

时间:2018-03-24 18:44:50

标签: javascript vuejs2 axios

试图将我的API与Vue / Axios集成,遇到麻烦。基本上,Axios正在获取数据(它是DOES console.log我想要的)...但是当我尝试将该数据传递给我的空变量(在我的组件的数据对象中)来存储它时,它会抛出“undefined”在eval“错误。关于为什么这对我不起作用的任何想法?谢谢!

<template>
  <div class="wallet-container">
    <h1 class="title">{{ title }}</h1>
    <div class="row">
      {{ thoughtWallet }}
    </div>
  </div>
</template>

<script>

import axios from 'axios';
export default {

  name: 'ThoughtWallet',
  data () {
    return {
      title: 'My ThoughtWallet',
      thoughtWallet: [],
    }
  },
  created: function() {
    this.loadThoughtWallet();
  },
  methods: {
    loadThoughtWallet: function() {
      this.thoughtWallet[0] = 'Loading...',
      axios.get('http://localhost:3000/api/thoughts').then(function(response) {
        console.log(response.data); // DISPLAYS THE DATA I WANT
        this.thoughtWallet = response.data; // THROWS TYPE ERROR: Cannot set property 'thoughtWallet' of undefined at eval
      }).catch(function(error) {
        console.log(error);
      });
    }
  }
}

</script>

2 个答案:

答案 0 :(得分:4)

this.thoughtWallet方法中的

.get指的是axios对象,而不是Vue。您可以在开头简单地定义Vue this

methods: {
  loadThoughtWallet: function() {
    let self = this;

    this.thoughtWallet[0] = 'Loading...',
    axios.get('http://localhost:3000/api/thoughts').then(function(response) {
      console.log(response.data); // DISPLAYS THE DATA I WANT

      self.thoughtWallet = response.data;

    }).catch(function(error) {
      console.log(error);
    });
  }
}

答案 1 :(得分:4)

因为您正在使用.then(function(..) { }) this,所以不会引用vue上下文this

你有两个解决方案,一个是在axios调用之前设置一个引用你想要的this的变量,例如:

var that = this.thoughtWallet
axios.get('http://localhost:3000/api/thoughts').then(function(response) {
        console.log(response.data); // DISPLAYS THE DATA I WANT
        that = response.data; // THROWS TYPE ERROR: Cannot set property 'thoughtWallet' of undefined at eval
      }).catch(function(error) {
        console.log(error);
      });

另一种方法是使用新语法(您需要确保您的代码已正确转换为不支持它的浏览器),这样您就可以访问范围内的this然后是axios的身体。

axios.get('http://localhost:3000/api/thoughts').then((response) => {
        console.log(response.data); // DISPLAYS THE DATA I WANT
        this.thoughtWallet = response.data; // THROWS TYPE ERROR: Cannot set property 'thoughtWallet' of undefined at eval
      }).catch(function(error) {
        console.log(error);
      });

发生这种情况的原因是因为在函数内部,this将引用函数的上下文,因此不会成为thoughtWallet属性

相关问题