簡體   English   中英

Vue.js - 嘗試存儲和顯示 vue-axios 響應數據時未定義 axios

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM