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.
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.
This package seems to be a good solution for the underlying issue of having non-unique IDs in your DOM across multiple components:
vue-uniq-ids
It can also be achieved using this pattern (Vue 2.0 v-bind) , so let say you have a list of items to iterate over and you want to give some dom element uninque id's.
Html
Hope it helps
Each component has a unique id which can be accessed as
this._uid
.If you want more control over the ids you can for example, generate them inside a parent component.
To Nihat's point (above): Evan You has advised against using _uid: "The vm _uid is reserved for internal use and it's important to keep it private (and not rely on it in user code) so that we keep the flexibility to change its behavior for potential future use cases. ... I'd suggest generating UIDs yourself [using a module, a global mixin, etc.]"
Using the suggested mixin in this GitHub issue to generate the UID seems like a better approach: