added form/control support

This commit is contained in:
2023-02-17 12:37:21 +10:00
parent d1e586bb39
commit e97427c7d7

View File

@@ -2,7 +2,7 @@
<div :class="['form-group', { 'has-error': error }]">
<label v-if="label" :class="{ required: required }">{{ label }}</label>
<select
:value="modelValue"
:value="value"
@input="input"
@blur="handleBlur"
@keydown="handleBlur">
@@ -10,7 +10,7 @@
v-for="(value, key) in options"
:key="key"
:value="key"
:selected="modelValue == value">
:selected="value == value">
{{ value }}
</option>
</select>
@@ -26,7 +26,9 @@
</template>
<script setup lang="ts">
import { useSlots, onMounted, computed, watch } from "vue";
import { useSlots, ref, computed, watch, inject } from "vue";
import { isEmpty } from "../helpers/utils";
import { toTitleCase } from "../helpers/string";
const props = defineProps({
modelValue: {
@@ -63,10 +65,31 @@ const props = defineProps({
type: String,
default: "",
},
control: {
type: String,
default: "",
},
form: {
type: Object,
default: () => {
return {};
},
required: false,
},
feedbackInvalid: {
type: String,
default: "",
},
});
const emits = defineEmits(["update:modelValue", "blur"]);
const slots = useSlots();
const objForm = inject("form", props.form);
const objControl =
!isEmpty(objForm) && props.control != "" ? objForm[props.control] : null;
const label = ref("");
const value = ref(props.modelValue);
const feedbackInvalid = ref("");
const input = (event) => {
emits("update:modelValue", event.target.value);
@@ -78,18 +101,47 @@ const handleBlur = (event) => {
}
};
watch(
() => props.label,
(newValue) => {
label.value = newValue;
}
);
const initialOptions = computed(() => {
return props.options;
});
watch(initialOptions, () => {
if (
props.modelValue.length > 0 &&
props.modelValue in Object.keys(props.options) == true
value.value.length > 0 &&
value.value in Object.keys(props.options) == true
) {
emits("update:modelValue", props.modelValue);
emits("update:modelValue", value);
} else if (Object.keys(props.options).length > 0) {
emits("update:modelValue", Object.keys(props.options)[0]);
}
});
if (objControl) {
if (value.value.length > 0) {
objControl.value = value.value;
} else {
value.value = objControl.value;
}
if (label.value.length == 0) {
label.value = toTitleCase(props.control);
}
watch(
() => objControl.validation.result.valid,
(newValue) => {
feedbackInvalid.value = newValue
? ""
: objControl.validation.result.invalidMessages[0];
},
{ deep: true }
);
}
</script>