[Vuejs]-Vue JS Radio button toggle all scenario

2👍

If you don’t have any specific preference for the checked states, I would recommend using a list of boolean and toggle their respective states (with Vue.set to overcome the array change detection caveat).

The example below uses a computed setter/getter to reactively tell if all checkboxes are checked, and toggle them at once when the setter gets called.

By the way, I added an extra attribute (indeterminate) that you might find useful.

I’m using the .prop modifier on the "allChecked" checkbox to tell Vue that we want to bind this indeterminate as a DOM property instead of component attribute.

new Vue({
  el: '#app',
  data() {
    return {
      checkList: [false, false, false, false]
    }
  },
  computed: {
    allChecked: {
      get() {
        return this.checkList.every(Boolean);
      },
      set(isChecked) {
        for (let index = 0; index < this.checkList.length; index++) {
          this.$set(this.checkList, index, isChecked);
        }
      }
    },
    indeterminate() {
      return !this.allChecked && this.checkList.some(Boolean);
    }
  }
})
#app > input[type="checkbox"] {
  display: block;
}
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script>

<div id="app">
  <label>
  <input 
    v-model="allChecked"
    :indeterminate.prop="indeterminate"
    class="toggleAll" 
    type="checkbox" />
  Check all
  </label>

  <input 
    v-model="checkList[index]" 
    v-for="(checked, index) of checkList" :key="index"  
    class="radio" 
    type="checkbox" />
</div>

-2👍

It could be that your problem comes from the fact that the @change event only fires when a user interacts with the radio and changes. On the other hand, looking at your code, are you trying to change the main button’s status using the checkAll method? In that case, what’s the toggleAll referencing in @change="toggleAll"?

In any case, this should do it:

<template>
    <div>
        <input class="toggleAll" type="checkbox" :checked="checked2" @change="toggleAll">

        <input :checked="checked" @change="toggleMain" class="radio" type="checkbox">
        <input :checked="checked" @change="toggleMain" class="radio" type="checkbox">
        <input :checked="checked" @change="toggleMain" class="radio" type="checkbox">
         <input :checked="checked" @change="toggleMain" class="radio" type="checkbox">
    </div>
</template>

<script>

    export default {
        name: 'SomeComponent',
        data() {
            return {
                checked: false,
                checked2: false
            {
        },
        methods: {
            toggleMain() {
                this.checked2 = false;
            }
            ...
        }
    }
</script> 

Leave a comment