logaretm / vee-validate

✅ Painless Vue forms
https://vee-validate.logaretm.com/v4
MIT License
10.81k stars 1.26k forks source link

useField type=checkbox does not work properly with v-model #3997

Closed demyan1411 closed 1 year ago

demyan1411 commented 1 year ago

What happened?

v-model not work properly with custom checkboxes in Your example.
https://vee-validate.logaretm.com/v4/examples/custom-checkboxes/

<div>checkedNames: {{ checkedNames }}</div>

<CustomCheckbox v-model="checkedNames" name="drinks" value="☕️" />
<CustomCheckbox v-model="checkedNames" name="drinks" value="🍵" />
<CustomCheckbox v-model="checkedNames" name="drinks" value="🥤" />

Expected array with choosed values, but get one value

Version

Vue.js 3.x and vee-validate 4.7.2

What browsers are you seeing the problem on?

Demo link

https://stackblitz.com/edit/vee-validate-v4-custom-checkboxes-fdbcgh?file=src%2FApp.vue

Code of Conduct

logaretm commented 1 year ago

Not a bug, groups like checkboxes must be wrapped in a <Form> or useForm(), otherwise there is no way it can tell it is a part of a checkbox group.

https://stackblitz.com/edit/vee-validate-v4-custom-checkboxes-xecm3v?file=src%2FApp.vue,package.json

demyan1411 commented 1 year ago

@logaretm but Field type=checkbox can work without Form!
Why useField can not?
https://github.com/logaretm/vee-validate/issues/3105

logaretm commented 1 year ago

Yes, it can work but not as a group because it has no idea it is part of a group of checkboxes. a form component/composable provides that context.

Basically, let's say you have the following example:

<Field v-model="model" type="checkbox" name="field" :value="'test'"  />

How should that field set the model value? should it set it to 'test' or ['test']? You can argue if the model value is an array it can be safe to assume that it should be ['test'] but I would rather stay away from assumptions.

So a form fixes that by telling the field it has no other siblings with the same name so it should set the value to 'test' directly.

demyan1411 commented 1 year ago

@logaretm But now Field works with array! Only useField cannot

https://stackblitz.com/edit/vee-validate-v4-custom-checkboxes-slltaj?file=src%2FApp.vue

And it works like native Vue3 https://vuejs.org/guide/essentials/forms.html#checkbox

demyan1411 commented 1 year ago

@logaretm I understand how to do it.
https://stackblitz.com/edit/vee-validate-v4-custom-checkboxes-dw8pwy?file=src%2Fcomponents%2FCustomCheckbox.vue

initialValue: props.modelValue,