2017-05-13 16 views
1

我有一個對象數組叫做它來自API調用的「文章」,我正在使用v-for循環來顯示它們。在vue.js的v-for循環中檢索一個id

現在,當用戶點擊其中一篇文章時,我想檢索該ID,以便我可以使用它到$ router.push查詢字符串。

問題是,由於文章是一個數組,我需要正確的索引來檢索ID。如何實現這一目標?

下面是示例HTML:

 <article v-for="(article, index) in articles" v- 
     on:click="displayArticle" :index="index"> 
      <h4>{{ article.title }}</h4> 
      <p>{{ article.text }}</p> 
     </article> 

這裏是一個示例代碼vue.js

export default { 
data() { 
    return { 
     articles: [] 
    } 
}, 
// here I avec a create() that make an API call and push the json in articles. 

methods : { 
    displayArticle: function() { 
    // I don't know ho to retrieve the index 

    // The router part would be something like this 
    this.$router.push({ path: '/app/?article_id=', query : {article_id: articleId}} 
    } 
} 

我試着用裁判,但我只是得到另一個陣列。

謝謝您的幫助

+0

的關鍵是必需的。 https://vuejs.org/v2/guide/list.html#Components-and-v-for – Bert

回答

0

v-on:click="displayArticle(index)" - 只是通過索引你的函數。

如果您的每篇文章的ID不等於數組中的位置(我認爲不是),那麼您應該在服務器發送的數據中包含每篇文章的ID(以及article.title,article.text應該有article.id)。

+1

更好的是,只需通過文章。 – Bert

+0

@BertEvans絕對。 – wostex

0

非常感謝,我通過在功能上的文章和我一起

this.articles.indexOf(article); 

感謝檢索,並有一個美好的一天迭代組件時

+0

如果你通過文章,你已經有了,你不必從數組中拉出它。 – Bert

+0

是的,我注意到了。我可以使用article.id。謝謝 – Nicci