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

标签 javascript vuejs2 axios

在尝试将我的 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>

最佳答案

因为你正在使用 .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 inside然后是 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);
      });

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

关于javascript - 使用 Axios 和 Vue 获取 api 数据 - 返回 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49468509/

相关文章:

javascript - 抓取指定的图像源并将其添加到输入表单中

javascript - 有没有办法在 Vue JS 的列表渲染(v-for)中使用条件渲染

javascript - Vue DOM 更新不会在第一次点击时发生,在后续点击中起作用

javascript - Vue.js 2 - 从重新填充的列表中选择的项目不刷新更改

node.js - 使用 express 在 axios post 请求后进行重定向

javascript - 尝试使用 axios 时出现网络错误

java - 十六进制字符串到 ByteArray

javascript - 如何使用最接近的和 parent 的javascript方法来获取 Angular 6中的td值

reactjs - Axios 进入 .then 未按预期工作

javascript - 从 SCEditor 获取值