使用Axios和Vue提取api数据-返回未定义

Cor*_*ush 1 javascript axios vuejs2

尝试将我的API与Vue / Axios集成时遇到麻烦。基本上,Axios正在获取数据(它确实是console.log我想要的)...但是当我尝试将数据获取到我的空变量(在组件的数据对象中)以存储它时,它会抛出“未定义”评估时”错误。有什么想法为什么对我不起作用?谢谢!

<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>
Run Code Online (Sandbox Code Playgroud)

m3c*_*ers 5

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

您有两种解决方案,一种是this在axios调用之前设置一个引用所需变量的变量,例如:

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);
      });
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用新语法(对于不支持该语法的浏览器,您需要确保对其进行正确的代码转换),这使您可以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);
      });
Run Code Online (Sandbox Code Playgroud)

发生这种情况的原因是因为在该函数中/然后this将引用该函数的上下文,因此不会有thoughtWallet属性