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