How Check all checkboxes with Vue.js?

Sometimes, we want to check all checkboxes with Vue.js.

In this article, we’ll look at how to check all checkboxes with Vue.js.

Check All Checkboxes with Vue.js

To check all checkboxes with Vue.js, we can add a change event listener to the checkbox that checks all the other checkboxes.

For instance, we write:

<template>
  <div id="app">
    <table>
      <tr>
        <th>
          <input type="checkbox" v-model="allSelected" @change="selectAll" />
        </th>
        <th align="left">select all</th>
      </tr>
      <tr v-for="user of users" :key="user.id">
        <td>
          <input type="checkbox" v-model="selected" :value="user.id" number />
        </td>
        <td>{{ user.name }}</td>
      </tr>
    </table>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      users: [
        { id: "1", name: "jane smith", email: "[email protected]" },
        { id: "2", name: "john doe", email: "[email protected]" },
        { id: "3", name: "dave jones", email: "[email protected]" },
        { id: "4", name: "alex smith", email: "[email protected]" },
      ],
      selected: [],
      allSelected: false,
    };
  },
  methods: {
    async selectAll() {
      if (this.allSelected) {
        const selected = this.users.map((u) => u.id);
        this.selected = selected;
      } else {
        this.selected = [];
      }
    },
  },
};
</script>

We have the users array that’s rendered in a table.

In the template, we have a table row for the select all checkbox.

And below that, we use the v-for directive to render the checkboxes from the users data.

We set v-model to selected so we can set it to the values we want.

And we set the value prop of each checkbox to user.id so that we can put the user.id values for the users we want to select into the selected array.

We set the selectAll method as the change handler for the select all checkbox.

In selectAll, set check if this.allSelected is true.

If it’s true, then we set this.selected to an array with the id values from each this.users entry to select all the checkboxes.

Otherwise, we set this.selected to an empty array to deselect all checkboxes.

Conclusion

To check all checkboxes with Vue.js, we can add a change event listener to the checkbox that checks all the other checkboxes.