簡體   English   中英

如何將從 API 獲取的數組分配給 Vue.js 中的數據屬性?

[英]How to assign array fetched from an API to data property in Vue.js?

我試圖從外部來源獲取新聞文章,它返回 JSON 對象。 我想將它的文章屬性分配給我組件中的一個變量。 不知何故,這個錯誤正在發生。

未捕獲(承諾)類型錯誤:無法設置未定義的屬性“文章”

關於如何克服這個問題的任何建議?

export default {
  name: "blog",
  data() {
    return {
      articles: [],
    };
  },
  mounted() {
    // API call
    this.fetchnews();
  },
  methods: {
    fetchnews(){
      fetch(
      "----------------------news link-------------------------"
    )
      .then(function(response) {
        return response.json();
      })
      .then(function(json_data) {
        //console.log(typeof(json_data))
        this.articles = json_data.articles
      });
    }
  }
};

正如第一個貢獻者正確注意到的那樣 - 問題是您最新功能中的this.articles並沒有真正指向您需要的內容。 如果您僅限於 ES5,那么請堅持第一個答案。 但是,如果您可以使用 ES6,那么只需獲得簡短語法的優勢:

export default {
  name: "blog",
  data() {
    return {
      articles: [],
    };
  },
  mounted() {
    // API call
    this.fetchnews();
  },
  methods: {
    fetchnews(){
      fetch("----------------------news link-------------------------")
      .then(response => response.json())
      .then(json_data => this.articles = json_data.articles);
    }
  }
};
  • 在這種情況下, this將正確指向外部作用域。

另外你為什么需要兩個then() 您可以將它們合二為一:

.then(response => this.articles = response.json().articles);

this.articles :這里this指的是函數而不是 vue instance ,所以你可以在函數外定義 this ,如:

let This=this

在你的函數中:

This.articles = json_data.articles這里指的是vue實例

使用function關鍵字創建新的作用域。 如果你使用像() => {}這樣的箭頭語法,你可以使用父作用域並通過this.articles設置文章

fetchnews(){
  fetch()
  .then((response) => {
    return response.json();
  })
  .then((json_data) => {
    this.articles = json_data.articles
  });
}

javascript function作為全局范圍確保用於將函數分配給變量

暫無
暫無

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

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