Vue.js : How to set a unique ID for each component instance?

PierreB picture PierreB · Jan 22, 2016 · Viewed 91.8k times · Source

I want to create a component with Vue.js containing a label and an input. for example :

<label for="inputId">Label text</label>
<input id="inputId" type="text" />

How can I set a unique ID for each component instance?

Thank you.

Answer

zxzak picture zxzak · Jan 22, 2016

Each component has a unique id which can be accessed as this._uid.

<template>
  <div>
    <label :for="id">Label text for {{id}}</label>
    <input :id="id" type="text" />
  </div>
</template>

<script>
export default {
  data () {
    return {
      id: null
    }
  }, 
  mounted () {
    this.id = this._uid
  }
}
</script>

If you want more control over the ids you can for example, generate them inside a parent component.