opnform/resources/js/components/forms/useFormInput.js

76 lines
2.0 KiB
JavaScript
Raw Normal View History

2023-10-24 09:00:54 +00:00
import { ref, computed, watch } from 'vue'
2023-10-19 08:46:04 +00:00
import { themes } from '~/config/form-themes.js'
export const inputProps = {
id: { type: String, default: null },
name: { type: String, required: true },
label: { type: String, required: false },
form: { type: Object, required: false },
2023-11-17 11:56:12 +00:00
modelValue: { required: false },
2023-10-19 08:46:04 +00:00
required: { type: Boolean, default: false },
disabled: { type: Boolean, default: false },
placeholder: { type: String, default: null },
uppercaseLabels: { type: Boolean, default: false },
2023-10-28 10:17:50 +00:00
hideFieldName: { type: Boolean, default: false },
2023-10-19 08:46:04 +00:00
help: { type: String, default: null },
helpPosition: { type: String, default: 'below_input' },
theme: { type: Object, default: () => themes.default },
color: { type: String, default: '#3B82F6' },
wrapperClass: { type: String, default: 'relative mb-3' }
}
2023-10-24 09:00:54 +00:00
export function useFormInput (props, context, formPrefixKey = null) {
2023-10-19 08:46:04 +00:00
const content = ref(props.modelValue)
const inputStyle = computed(() => {
return {
'--tw-ring-color': props.color
}
})
const hasValidation = computed(() => {
return props.form !== null && props.form !== undefined && props.form.hasOwnProperty('errors')
})
const hasError = computed(() => {
2023-10-28 10:17:50 +00:00
return hasValidation && props.form?.errors?.has(name)
2023-10-19 08:46:04 +00:00
})
const compVal = computed({
get: () => {
if (props.form) {
2023-10-24 09:00:54 +00:00
return props.form[(formPrefixKey || '') + props.name]
2023-10-19 08:46:04 +00:00
}
return content.value
},
set: (val) => {
if (props.form) {
2023-10-24 09:00:54 +00:00
props.form[(formPrefixKey || '') + props.name] = val
2023-10-19 08:46:04 +00:00
} else {
content.value = val
}
if (hasValidation.value) {
props.form.errors.clear(props.name)
}
2023-10-24 09:00:54 +00:00
context.emit('update:modelValue', compVal.value)
2023-10-19 08:46:04 +00:00
}
})
// Watch for changes in props.modelValue and update the local content
watch(
() => props.modelValue,
(newValue) => {
content.value = newValue
}
)
return {
compVal,
inputStyle,
hasValidation,
hasError
}
}