簡體   English   中英

使用Axios和Vue提取api數據-返回未定義

[英]Using Axios and Vue to fetch api data - returning undefined

嘗試將我的API與Vue / Axios集成時遇到麻煩。 基本上,Axios正在獲取數據(它確實是console.log我想要的)...但是,當我嘗試將數據獲取到我的空變量(在組件的數據對象中)進行存儲時,它會拋出“未定義”評估時”錯誤。 有什么想法為什么對我不起作用? 謝謝!

<template>
  <div class="wallet-container">
    <h1 class="title">{{ title }}</h1>
    <div class="row">
      {{ thoughtWallet }}
    </div>
  </div>
</template>

<script>

import axios from 'axios';
export default {

  name: 'ThoughtWallet',
  data () {
    return {
      title: 'My ThoughtWallet',
      thoughtWallet: [],
    }
  },
  created: function() {
    this.loadThoughtWallet();
  },
  methods: {
    loadThoughtWallet: function() {
      this.thoughtWallet[0] = 'Loading...',
      axios.get('http://localhost:3000/api/thoughts').then(function(response) {
        console.log(response.data); // DISPLAYS THE DATA I WANT
        this.thoughtWallet = response.data; // THROWS TYPE ERROR: Cannot set property 'thoughtWallet' of undefined at eval
      }).catch(function(error) {
        console.log(error);
      });
    }
  }
}

</script>

this.thoughtWallet里面.get方法指的是愛可信對象,而不是Vue公司的。 你可以簡單地定義Vue公司的this對啟動:

methods: {
  loadThoughtWallet: function() {
    let self = this;

    this.thoughtWallet[0] = 'Loading...',
    axios.get('http://localhost:3000/api/thoughts').then(function(response) {
      console.log(response.data); // DISPLAYS THE DATA I WANT

      self.thoughtWallet = response.data;

    }).catch(function(error) {
      console.log(error);
    });
  }
}

因為您使用的是.then(function(..) { }) this不會引用vue上下文this

你有兩個解決方案,一個是設置引用變量this你愛可信調用,如前想:

var that = this.thoughtWallet
axios.get('http://localhost:3000/api/thoughts').then(function(response) {
        console.log(response.data); // DISPLAYS THE DATA I WANT
        that = response.data; // THROWS TYPE ERROR: Cannot set property 'thoughtWallet' of undefined at eval
      }).catch(function(error) {
        console.log(error);
      });

另一種方法是使用新的語法(對於不支持該語法的瀏覽器,您需要確保對其進行正確的代碼轉換),這樣您便可以在axios的作用域內部訪問this語法。

axios.get('http://localhost:3000/api/thoughts').then((response) => {
        console.log(response.data); // DISPLAYS THE DATA I WANT
        this.thoughtWallet = response.data; // THROWS TYPE ERROR: Cannot set property 'thoughtWallet' of undefined at eval
      }).catch(function(error) {
        console.log(error);
      });

發生這種情況的原因是因為在該函數中/然后, this將引用該函數的上下文,因此不會有一個thoughtWallet屬性

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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