My Vue3 form has three text inputs and a group of checkboxes. To implement this, I am using the bootstrap-vue form along with its checkbox-group component.
After calling an API to fetch default values for the form, I update the ref as shown below. Interestingly, the text inputs all get updated correctly.
However, I encountered an issue with the checkbox group component. Even though the checked items are present in the tagList ref, they do not get checked.
// In this composable, I set the formValues ref and make an API call to retrieve default values.
// taglist will be a list of strings: tagList = ['example']
const formValues = ref<IArticleFormValues>({
title: '',
body: '',
description: '',
tagList: [],
});
const { data, isFetching } = useQuery({
queryKey: ['fetchArticleBySlug', slug],
queryFn: () => fetchSingleArticleService(slug)
});
watch(data, () => {
if (data.value?.article) {
formValues.value = {
...data.value.article,
tagList: data.value.article.tagList.map((item) => item),
};
}
});
// Then, I inject this data using vue inject like so
provide(formInjectionKey, { formValues });
Let's take a look at the checkbox-group component. The 'tags' variable represents a list of options formatted like this:
tags = [{text:'example',value:'example'}]
The 'tagList' will be structured similarly to this:
tagList = ['example']
<script setup lang="ts">
import CustomCheckboxGroup from '@/components/DesignSystem/components/CustomCheckboxGroup.vue';
import { inject } from 'vue';
const { formValues } = inject(formInjectionKey);
</script>
<template>
<CustomCheckboxGroup v-else :options="tags" v-model="formValues.tagList" />
</template>
Lastly, here is the code for the CustomCheckboxGroup component:
// CustomCheckboxGroup.vue
<script setup lang="ts">
defineProps<{ value?: any[]; options: any[] }>();
</script>
<template>
<b-form-group>
<b-form-checkbox-group
:value="value"
@input="$emit('input', $event)"
:options="options"
v-bind="$attrs"
stacked
></b-form-checkbox-group>
</b-form-group>
</template>