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.)
Import the ref function from vue and define two variables:
import { ref } from 'vue';
const possibleCheckboxes = ["apple", "banana", "orange", "grape"];
const savedCheckboxes = ref(["banana", "orange"]);
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>
Create a method onCheckboxChange(value, isChecked) that:
function onCheckboxChange(value, isChecked) {
if (isChecked) {
if (!savedCheckboxes.value.includes(value)) {
savedCheckboxes.value.push(value);
}
} else {
savedCheckboxes.value = savedCheckboxes.value
.filter((v) => v !== value);
}
}
Tip: If you’re saving to a backend, watch savedCheckboxes with watch() or trigger an API call inside onCheckboxChange.
Work with our skilled Vue developers to accelerate your project and boost its performance.
Hire Vuejs Developers