Search code examples
vue.jsvue-componentv-for

Using v-for on a custom component, can I access the value of ":key" inside of the component?


When using v-for to create a list of custom components, I often find myself binding the item.id to the value of my :key and :id props. I'm wondering if (and if so, how) I can access the value of key, perhaps as a prop inside of my component. This would effectively save me the hassle of having to create an id prop on every component that uses a v-for directive.

<my-component v-for="item in items" :key="item.id" :id="item.id"></my-component>
// MyComponent.vue
props: ['key']

Registering key as a prop and using this.key in the app produces a value of undefined. So clearly I can't simply reference the key as a prop.

Suggestions?


Solution

  • I've been asking around and it looks like the value of key is used more for Vue's virtual DOM which makes it far less usable as a data property within the component itself. Because the virtual DOM can change, the value of key may change out-of-sync to the data's intended id property, if Vue finds it efficient to do so. This makes using it to reference the id of a specific object in data unreliable.

    If someone else has a better explanation, please share.