Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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".

like image 529
angrykoala Avatar asked Dec 12 '17 23:12

angrykoala


People also ask

How do you access child components at Vue?

To access child component's data from parent with Vue. js, we can assign a ref to the child component. And then we can access the child component data as a property of the ref. to assign the markdown ref to the markdown component.

How do you access a root component from a child instance in Vue?

Conclusion. We can access the root Vue instance with $root , and the parent component with $parent . To access a child component from a parent, we can assign a ref with a name to the child component and then use this. $refs to access it.

How do you call parent method from child component in Vue?

To call parent method with component with Vue. js, we can get the parent component's method from the $parent property. to define the child component with Vue. component .


1 Answers

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.

like image 172
Decade Moon Avatar answered Oct 17 '22 23:10

Decade Moon