[英]Vue.js - Trouble displaying results from API call in component
嘗試使用 Vue.js,嘗試使用 v-for 指令在組件中顯示來自 Wikipedia API 調用的結果,但后端無法正常工作,我不知道它是什么。
鏈接到jsFiddle
HTML
<div id="app">
<input type="text" v-model="searchTerm" v-on:keyup="getResults">
<searchResult
v-for="item in results"
v-bind:result="item"
v-bind:key="item.key"
></searchResult>
</div>
Javascript
new Vue({
el: '#app',
data: {
api: "https://en.wikipedia.org/w/api.php?",
searchTerm: 'Ron',
searchDataString: "action=opensearch&format=json&origin=*&uselang=user&errorformat=html&search="+this.searchTerm+"&namespace=0%7C4&limit=20&profile=fuzzy",
searchCall: this.api+""+this.searchDataString,
results: []
},
methods: {
getResults() {
this.searchCall = this.api+"action=opensearch&format=json&origin=*&uselang=user&errorformat=html&search="+this.searchTerm+"&namespace=0%7C4&limit=20&profile=fuzzy";
//console.log( this.searchCall );
axios.post( this.searchCall )
.then(response => { this.processResults(response.data) });
},
processResults(data) {
//console.log( data );
for(var i = 0; i < data[1].length; i++) {
var resultItem = { key:i, link:data[3][i], name:data[1], description:data[2][i] };
this.results.push(resultItem);
console.log(resultItem);
}
}
}
});
Vue.component( "searchResult", {
props:['result'],
template: "<a target='_blank' href='{{ result.link }}'><div class='search-result'><h3>{{ result.name }}</h3><p>{{ result.description }}</p><div></a>"
});
我心中的兩個問題是
當我查看控制台中的數組時,它顯示的只是 getter 和 setter。 我是新手,所以也許這就是它應該做的。
我非常接近讓這個工作,但我無能為力,非常感謝幫助。
您的代碼的問題是 html 標簽不區分大小寫,因此命名組件searchResult
會導致問題。 如果您需要使用searchResult
,則必須在模板中使用<search-result>
。 我發現完全避免這個問題並給組件小寫名稱會更好。 以下是有關該問題的文檔: https ://v2.vuejs.org/v2/guide/components.html#Component-Naming-Conventions
您提到了“輸入輸入時在控制台中顯示的錯誤消息”。 復制和粘貼您的代碼時,我沒有收到任何錯誤(除了忘記包含 axios)。 你遇到了什么錯誤?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.