在 vue.js 中的 v-for 循环中检索 id
Retrieve an id in a v-for loop in vue.js
我有一个名为 "articles" 的对象数组,来自 API 调用,我正在使用 v-for 循环来显示它们。
现在,当用户单击其中一篇文章时,我想检索 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}}
}
}
我尝试使用 ref 但我只是得到另一个数组。
感谢您的帮助
v-on:click="displayArticle(index)"
- 只需将索引传递给您的函数。
如果每篇文章的 ID 不等于数组中的位置(我假设不是),那么您应该将每篇文章的 ID 包含在服务器发送的数据中(连同 article.title, article.text 应该有 article.id).
非常感谢,我在函数中传递了文章,并用
检索了它
this.articles.indexOf(article);
谢谢,祝你有美好的一天
我有一个名为 "articles" 的对象数组,来自 API 调用,我正在使用 v-for 循环来显示它们。
现在,当用户单击其中一篇文章时,我想检索 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}}
}
}
我尝试使用 ref 但我只是得到另一个数组。
感谢您的帮助
v-on:click="displayArticle(index)"
- 只需将索引传递给您的函数。
如果每篇文章的 ID 不等于数组中的位置(我假设不是),那么您应该将每篇文章的 ID 包含在服务器发送的数据中(连同 article.title, article.text 应该有 article.id).
非常感谢,我在函数中传递了文章,并用
检索了它this.articles.indexOf(article);
谢谢,祝你有美好的一天