尝试存储和显示vue-axios响应数据时axios未定义

时间:2018-10-05 21:45:43

标签: javascript vue.js vuejs2 axios

我似乎无法获得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;
        })
    }
  }
})
<!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>

2 个答案:

答案 0 :(得分:4)

我要补充@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;
        })
    }
  }
})
<!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>

答案 1 :(得分:2)

您缺少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>