Search code examples
checkboxvuejs3v-model

Vue 3 composition api checkbox v-model select all option is not working


I am testing a small vue 3 application. I trying to have a checkbox list with a select all option. Initially the select all option works. But after I select one element from the list individually the select all option stops working.

Here is the code I am testing:

<script setup>
import { reactive } from 'vue'

const selected = defineModel({ default: reactive([]) });

const items = [1, 2, 3, 4];
const selectAll = (item) => {
  selected.value.splice(0);
  if (item.checked) selected.value.push(...items);
};
</script>

<template>
  <div>
    <input type="checkbox" @click="selectAll($event.currentTarget)" />
    Select all
  </div>
  <div v-for="item in items" :key="item">
    <input type="checkbox" :value="item" v-model="selected" /> {{ item }}
  </div>
  {{ selected }}
</template>

Here you can run it in a test environment


Solution

  • First, you should create reactive references for the items array using the ref method.

    Then, the selectAll method updates the selected array based on the state of the "Select all" checkbox. If the checkbox is checked, all items are added to the selected array. If unchecked, the selected array is emptied.

    Here's the working code:

    <script setup>
    import { ref, reactive } from 'vue';
    
    const selected = defineModel({ default: reactive([]) });
    const items = ref([1, 2, 3, 4]);
    
    const selectAll = (event) => event.target.checked ? selected.value = [...items.value] : selected.value = []
    </script>
    
    <template>
      <div>
        <input type="checkbox" @change="selectAll($event)" />
        Select all
      </div>
      <div v-for="item in items" :key="item">
        <input type="checkbox" :value="item" v-model="selected" /> {{ item }}
      </div>
      {{ selected }}
    </template>
    

    Let me know if this helps or if you have any other questions.