2017-10-20 54 views
0

嘗試使用Vue.js,嘗試使用v-for指令在組件中顯示來自維基百科API調用的結果,但某些內容在後端不起作用,並且我不知道它是什麼。Vue.js - 在組件中顯示錯誤的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>" 
}); 

在我腦海的兩個問題是

  • ,顯示在控制檯時錯誤消息typi納克輸入,和
  • 的結果的陣列創建空的對象,而不是傳遞數據

當我看在控制檯陣列,所有這表明是getter和setter。我對此很陌生,所以也許這就是它應該做的。

我很接近這個工作,但我在我的智慧結束,非常感謝幫助。

+1

檢查小提琴鏈接,它只有最初的Vue代碼。 – yuriy636

+0

@ yuriy636哎呀,我救了它。現在應該顯示。 –

回答

0

您的代碼存在的問題是,html標籤不區分大小寫,因此命名組件searchResult會導致問題。如果您需要使用searchResult,則必須在模板中使用<search-result>。我發現最好只是爲了完全避免這個問題,並給出組件的小寫名稱。以下是有關該問題的文檔:https://vuejs.org/v2/guide/components.html#Component-Naming-Conventions

您提到了「輸入輸入時顯示在控制檯中的錯誤消息」。我沒有得到任何錯誤複製和粘貼你的代碼(除了忘記包含axios)。你遇到了什麼錯誤?