在VUE SFC内获取循环键

发布于 2025-01-30 17:19:43 字数 246 浏览 0 评论 0原文

给定以下循环组件:

<MyComponent v-for="(item, i) in items" :key="i" :item="item" />

如何获得myComponent中的值显然key是一个保留的单词,因此它无法作为一个支柱。

Given the following looping component:

<MyComponent v-for="(item, i) in items" :key="i" :item="item" />

How do I get the value of key within MyComponent obviously key is a reserved word so it fails to work as a prop.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

始终不够爱げ你 2025-02-06 17:19:43

将其作为声明的支架传递(例如:index):

<MyComponent v-for="(item, i) in items" :key="i" :item="item" :index="i" />

mycomponent.vue:

export default {
  props: {
    index: Number
  }
}

side注意:建议您使用唯一标识符列出 lists(例如:id id < /code>),而不是基于其在列表中的位置。例如,如果任何项目被更换或更新,VUE可能不会重新渲染,因为即使项目本身具有,这些项目在数组中的位置也没有更改。

这就是为什么您按索引关键项目时列表过渡不起作用的原因。

但是,如果您的项目不更改位置和/或不更新,则index作为key执行工作。

Pass it as a declared prop (e.g: index):

<MyComponent v-for="(item, i) in items" :key="i" :item="item" :index="i" />

MyComponent.vue:

export default {
  props: {
    index: Number
  }
}

Side note: it's recommended you key lists using a unique identifier (e.g: id) rather than based on their position in the list. For example, if any items get replaced or updated, Vue might not re-render, because the items' position in the array has not changed, even if the item itself has.

This is why list transitions don't work when you key items by index.

However, if your items don't change position and/or do not get updated, index as key does the job.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文