I cannot seem to able to get vue-axios
to fetch, store and display data in browser. I tried this and getting undefined
when getData
button is clicked.
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>
I would add to @boussadjrabrahim
's excellent answer that you need to use a fat arrow notation inside your then
callback to make sure that the this
keyword is bound to your Vue instance. Otherwise your dataReceived
will remain blank.
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>
You're missing axios
library so add it as follow :
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Another thing to rectify is this.response
change it to 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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.