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.
Update
I published the vue-unique-id Vue plugin for this on npm.
Answer
None of the other solutions address the requirement of having more than one form element in your component. Here's my take on a plugin that builds on previously given answers:
This doesn't rely on the internal
_uid
property which is reserved for internal use.Use it like this in your component:
To produce something like this:
Then in your code...
This way you're not loading the entire lodash library, or even saving the entire library to
node_modules
.If your uid is not used by other compoment, I have an idea.
uid: Math.random()
Simple and enough.
In Vue2, use v-bind.
Say I have an object for a poll
Update: Code will throw an error if
._uid
property does not exist in the instance so that you can update it to use something custom or new unique id property if provided by Vue.Although zxzak's answer is great;
_uid
is not a published api property. To save a headache in case it changes in the future, you can update your code with just one change with a plugin solution like below.A simple approach that I haven't seen in the replies is: