How to access key from child component with Vue.js?

Sometimes, we want to access key from child component with Vue.js.

In this article, we’ll look at how to access key from child component with Vue.js.

How to access key from child component with Vue.js?

To access key from child component with Vue.js, we should pass in the key value as a prop.

For instance, we write:

<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>

<div id='app'>

</div>

to add the Vue script and the app container.

Then we write:

const Foo = {
  template: `<p>{{index}}</p>`,
  props: ['index']
}

const v = new Vue({
  el: '#app',
  template: `
    <div>
    	<foo :key='i' :index='i' v-for='i of arr' />
    </div>
  `,
  data: {
    arr: [1, 2, 3, 4, 5]
  },
  components: {
    Foo
  }
})

to define the Foo component that takes the index prop.

And then we use v-for to loop through arr and render the foo component with the index prop set to i, which is an entry of arr.

key is reserved so we can’t use it as a prop name.

We also have to register Foo in the components property to render Foo.

Therefore, we see:

1

2

3

4

5

rendered.

Conclusion

To access key from child component with Vue.js, we should pass in the key value as a prop.