[英]How to assign array data retrieved from state to v-model of array data object in 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.