Oleg Bolden
Oleg Bolden

Reputation: 111

Why "checked" property and v-model can not be used together in Vue?

I'd like to know why "checked" property in a series of input checkbox elements become unaccessible if v-model is used in these elements in Vue.

Recently I tried to add CheckAll functionality to a list of items. Without v-model it's trivial:

<input type="checkbox" v-model="checkAll">
<div class="list">
  <input v-for="item in items" :value="item.id" type="checkbox" :checked="checkAll">
</div>

But if I add v-model "toRemove" to each item in order to get an array of checked items, checkAll checkbox stops working:

<input type="checkbox" v-model="checkAll">
<div class="list">
  <input v-for="item in items" :value="item.id" type="checkbox" :checked="checkAll" v-model="toRemove">
</div>

It's interesting that "disable" property works well with V-model in a similar manner:

<input type="checkbox" v-model="checkAll">
<div class="list">
  <input v-for="item in items" :value="item.id" type="checkbox" :disabled="checkAll" v-model="toRemove">
</div>

I wonder why Vue does not allow both checkAll and an array of checked items via v-model at the same time.

Upvotes: 0

Views: 3501

Answers (1)

skirtle
skirtle

Reputation: 29112

Using v-model on a checkbox sets the checked property. You can't set checked to two different values at the same time.

See https://v2.vuejs.org/v2/guide/forms.html for more explanation of how v-model works with checkboxes.

In your case you would implement the check-all functionality just by populating the array toRemove with all the relevant item ids.

Using :checked="checkAll" to implement check-all functionality isn't really the right way to do it even if you aren't using v-model. There's a basic assumption baked into your template that all the checkboxes are either checked or unchecked, rather than being independent checkboxes. This may have appeared to work in a simple test case but ultimately it was never likely to hold together once you tried to make the checkboxes do something for real.

Upvotes: 3

Related Questions