moa*_*zem 4 javascript vue.js vue-component axios vuejs2
我似乎无法vue-axios在浏览器中获取、存储和显示数据。我试过这个,undefined当getData按钮被点击时得到。
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;
})
}
}
})Run Code Online (Sandbox Code Playgroud)
<!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>Run Code Online (Sandbox Code Playgroud)
我要补充@boussadjrabrahim一个很好的答案,即您需要在then回调中使用粗箭头符号来确保this关键字绑定到您的 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;
})
}
}
})Run Code Online (Sandbox Code Playgroud)
<!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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
256 次 |
| 最近记录: |