[英]Vue.js - axios is undefined when trying to store and display vue-axios response data
我似乎無法讓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
回調中使用@boussadjrabrahim
箭頭符號,以確保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; }) } } })
<!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>
您缺少axios
庫,因此將其添加如下:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
另一件要糾正的事情是this.response
將其更改為response.data
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.