Мне не удается заставить vue-axios извлекать, хранить и отображать данные в браузере.Я попробовал это и получил undefined при нажатии кнопки getData.
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; }) } } })
<!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 привязано к вашему экземпляру Vue.В противном случае ваш dataReceived останется пустым.
@boussadjrabrahim
then
this
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 библиотеки, поэтому добавьте ее следующим образом:
axios
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Еще одна вещь, которую нужно исправить - this.response измените ее на response.data
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; }) } } })