Search code examples
javascriptvue.jsvuejs2

Access key from child component in vue


According to Vue docs, binding a key is required to use custom components in a v-for:

<template v-for="(task,i) in tasks">
    <task-card v-bind:task="task" v-bind:key="i"></task-card>
</template>

I would like to use that key in the child component (task-card), but neither using this.key or adding key as a prop (is a reserved Vue keyword) works. Is there a way of doing this without passing yet another prop with the value "i"? Currently working with "vue": "^2.5.9".


Solution

  • If you want to pass data to the child, you should be using props (key is reserved so you'll have to name it something else).

    Otherwise you can access the key on the vnode within the component via this.$vnode.key.

    Vue 3

    For Vue 3 the API has changed. You will need to access the vnode from internal private instance like so: this.$.vnode.key. As far as I know this is undocumented and may change; use with caution.