Here’s the Vue.js solution (Composition API with ref) along with step-by-step documentation. It updates the list of saved checkboxes based on user interaction (checking adds to the array, unchecking removes it.)

Step 1: Import and initialize reactive variables

Import the ref function from vue and define two variables:

  • possibleCheckboxes: holds the list of all possible checkbox options.
  • savedCheckboxes: a reactive array that stores checked values.
import { ref } from 'vue';
const possibleCheckboxes = ["apple", "banana", "orange", "grape"];
const savedCheckboxes = ref(["banana", "orange"]);

Step 2: Display checkboxes using v-for

Loop through the possibleCheckboxes array using v-for and display a checkbox for each item.

<template>
 <div v-for="item in possibleCheckboxes" :key="item">
   <label>
     <input
       type="checkbox"
       :value="item"
       :checked="savedCheckboxes.includes(item)"
       @change="onCheckboxChange(item, $event.target.checked)"
     />
     {{ item }}
   </label>
 </div>
</template>

Step 3: Handle checkbox changes

Create a method onCheckboxChange(value, isChecked) that:

  • Adds the value to savedCheckboxes if it’s checked.
  • Removes it if it’s unchecked.
function onCheckboxChange(value, isChecked) {
 if (isChecked) {
   if (!savedCheckboxes.value.includes(value)) {
     savedCheckboxes.value.push(value);
   }
 } else {
   savedCheckboxes.value = savedCheckboxes.value
                             .filter((v) => v !== value);
 }
}

Summary / Note

  • This setup allows dynamic two-way interaction with checkboxes in Vue 3 using the Composition API.
  • The savedCheckboxes array always reflects the current selection state and updates automatically as users check or uncheck boxes.
  • You can use this array to persist data to a server, populate a form, or enable/disable features conditionally.
  • Make sure to use ref() for reactive arrays and access them via .value in the <script setup> context.

Tip: If you’re saving to a backend, watch savedCheckboxes with watch() or trigger an API call inside onCheckboxChange.

Need Help With Vue Development?

Work with our skilled Vue developers to accelerate your project and boost its performance.

Hire Vuejs Developers

Support On Demand!

Related Q&A