mardi 10 octobre 2017

In Vue, how to cancel a checkbox based on a condition?

I want to always have at least one checkbox checked but I mix the concepts of v-model and :checked.

The doc says:

v-model will ignore the initial value, checked or selected attributes found on any form elements. It will always treat the Vue instance data as the source of truth.

I can prevent my model to be modified but I can't prevent the checkbox to be checked...

Some code:

The template

<div class="wrapper" v-for="(s, id) in userOutputSeries" :key="id">
  <input type="checkbox" :id="id" :value="id" @change="preventIfLessThanOneChecked" :checked="s.active">
  <label :for="id"></label>
</div>

The model userOutputSeries

data () {
  return {
    userOutputSeries: {
      foo: {
        display: 'Awesome Foo',
        active: true
      },
      bar: {
        display: 'My Bar',
        active: false
      }
    }
  }
}

The preventIfLessThanOneChecked handler

preventIfLessThanOneChecked (event) {
  // I don't update the model so it stay at the same state
  // But only need to count the active series and do what we want.
  console.log(event.target.value, event.target.checked)
}

Any ideas to stop the native checkbox propagation?




Aucun commentaire:

Enregistrer un commentaire