我似乎无法让 vue-axios
在浏览器中获取、存储和显示数据。我尝试了这个并在单击 getData
按钮时得到 undefined
。
new Vue({
el: '#app',
data: {
dataReceived: '',
},
methods: {
getData() {
axios.get('https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD')
.then(function(response) {
this.dataReceived = this.response;
console.log(this.dataReceived);
return this.dataReceived;
})
}
}
})
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script src="https://unpkg.com/vue@2.5.17/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<button @click="getData" type="button">getData</button>
<p>dataReceived: {{ dataReceived }}</p>
</div>
</body>
</html>
最佳答案
我想在 @boussadjrabrahim
的出色回答中补充一点,您需要在 then
回调中使用粗箭头符号,以确保 this
关键字绑定(bind)到您的 Vue 实例。否则您的 dataReceived
将保持空白。
new Vue({
el: '#app',
data: {
dataReceived: '',
},
methods: {
getData() {
axios.get('https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD')
.then((response) => {
this.dataReceived = response.data;
console.log(this.dataReceived);
return this.dataReceived;
})
}
}
})
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script src="https://unpkg.com/vue@2.5.17/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/vue-axios@2.1.4/dist/vue-axios.min.js"></script>
</head>
<body>
<div id="app">
<button @click="getData" type="button">getData</button>
<p>dataReceived: {{ dataReceived }}</p>
</div>
</body>
</html>
关于javascript - Vue.js - axios 在尝试存储和显示 vue-axios 响应数据时未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52673641/