It seems like the issue you're facing is related to the state of the selectedItem not being preserved after a form submission that results in a validation error. This can happen if the state of the Vue component is reset or if the selectedItem is not properly bound to the v-model directive.
Here's a solution that ensures the selectedItem is properly bound and updated:
-
Make sure that the
v-modeldirective in theBaseFormSimpleSelectcomponent is correctly bound to theselectedItemref. -
Ensure that the
selectedItemis updated when theinitialSelectedItemprop changes. This can be done by watching theinitialSelectedItemprop. -
When you receive a validation error, make sure that the
selectedItemis not reset to its initial state unless that's the intended behavior.
Here's the updated BaseFormSimpleSelect.vue component with the necessary changes:
<script setup>
import { ref, watch, onMounted, watchEffect } from 'vue';
import { Listbox, ListboxLabel, ListboxButton, ListboxOption, ListboxOptions } from '@headlessui/vue';
import { CheckIcon, ChevronUpDownIcon } from '@heroicons/vue/24/solid';
const props = defineProps({
// ... other props
initialSelectedItem: {
type: Object,
default: null,
},
});
const selectedItem = ref(props.initialSelectedItem);
const emit = defineEmits(['update:modelValue']);
// Watch for changes in initialSelectedItem prop
watch(() => props.initialSelectedItem, (newValue) => {
selectedItem.value = newValue;
}, { immediate: true });
// Emit the selected item whenever it changes
watch(selectedItem, (newValue) => {
emit('update:modelValue', newValue);
});
// ... rest of the script
</script>
<template>
<!-- ... rest of the template -->
</template>
And in the parent component where you use BaseFormSimpleSelect, make sure to bind the v-model correctly:
<BaseFormSimpleSelect
:key="renderKey"
v-model="selectedRole" <!-- Make sure this is the correct model -->
:items="rolesOptions"
label="Roles"
:has-error="form.errors.roles"
:initial-selected-item="selectedRoles"
@selected-item="updateSelected('roles', $event)"
/>
In the script setup of the parent component, ensure that selectedRole is a ref and is used as the model for the BaseFormSimpleSelect component:
<script setup>
// ... other imports
import { ref } from 'vue';
// ... other setup code
const selectedRole = ref(null); // Initialize the selectedRole ref
// ... rest of the script
</script>
Make sure that selectedRole is properly initialized with the value you want to be selected by default. If the selectedRole should retain its value after a validation error, ensure that it's not being reset in your form submission logic.
By following these steps, the BaseFormSimpleSelect component should correctly track and highlight the selected item, even after a form submission with validation errors.