Home > Net >  Multiple custom checkboxes in Vue3 react differently when clikcing label vs input
Multiple custom checkboxes in Vue3 react differently when clikcing label vs input

Time:08-26

I have a custom checkbox where the input and a separate (custom) label flip the checked value. When checked is changed, a watch picks it up and $emits the value to the parent.

In the parent, I have two of the same Toggle components, however when I click the Toggle input, it only triggers the first toggle (unexpected). If I click the label, it triggers the correct toggle switch (as expected).

Can someone please explain what is happening here?

https://codesandbox.io/s/vue3-base-forked-3ppj0j?file=/src/components/Toggle.vue

The event being emitted is the same, regardless of clicking the label or the input, so why does one work and the other doesn't?

CodePudding user response:

Currently you have same id for both checkboxes. Id has to be unique so it actually is only applied to first element. As <label> is linked to checkbox via id - both labels are linked to 1st element.

Simplest solution is passing id value as a property:

https://codesandbox.io/s/vue3-base-forked-1mgcj3?file=/src/components/Page.vue

Another way would be to generate unique id with something like Vue UUID package. This way you don't need to pass anything from parent component

CodePudding user response:

In Toggle.vue, I change something and here is my answer.

<label  :for="label">
  <input :id="label" v-model="checked" type="checkbox" />
  <div  />
</label>
  • Related