1

I have a custom Vue component (vcheck) that has a checkbox with a label:

<input 
    v-model="val" 
    type='checkbox' 
    :true-value="trueValue" 
    :false-value="falseValue"
    id="v-check"
>
<label for="v-check">{{val == trueValue ? displayChecked : displayUnchecked}}</label>

but the problem is when I have multiple instances (in the parent component), the IDs of the checkboxes clash:

<vcheck v-model="val1" display-checked="Yes" display-unchecked="No"></vcheck>
<vcheck v-model="val2" display-checked="Tested" display-unchecked="Untested"></vcheck>

So when i click the 2nd checkbox label, the 1st one changes (since they both have the same ID). At the moment I removed IDs and just using @click event on labels. But is there a way to generate unique IDs for every instance of the component?

ierdna
  • 5,753
  • 7
  • 50
  • 84

1 Answers1

1

One option can be to pass the id also as props to vcheck:

<vcheck v-model="val1" display-checked="Yes" display-unchecked="No" id="123">
</vcheck>

and use that for checkbox:

<input 
    v-model="val" 
    type='checkbox' 
    :true-value="trueValue" 
    :false-value="falseValue"
    :id="id"
>

I will recommend to make the id prop mandatory if you use this.

tony19
  • 125,647
  • 18
  • 229
  • 307
Saurabh
  • 71,488
  • 40
  • 181
  • 244
  • 1
    That's a good suggestion but I would like to keep the declaration as minimal as possible. Plus it requires keeping track of IDs anyway. – ierdna Jan 25 '17 at 16:29