Skip to content

Commit

Permalink
feat: add form field autofocus configuration (#4550)
Browse files Browse the repository at this point in the history
* feat: add form field autofocus configuration
  • Loading branch information
Squall2017 authored Oct 3, 2024
1 parent aed31a5 commit 64428b9
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion packages/@core/ui-kit/form-ui/src/form-render/form-field.vue
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { ZodType } from 'zod';
import type { FormSchema, MaybeComponentProps } from '../types';
import { computed } from 'vue';
import { computed, nextTick, ref, watch } from 'vue';
import {
FormControl,
Expand Down Expand Up @@ -52,6 +52,16 @@ const errors = useFieldError(fieldName);
const formApi = formRenderProps.form;
const isInValid = computed(() => errors.value?.length > 0);
const fieldComponentRef = ref<HTMLInputElement | null>(null);
const focus = () => {
if (
fieldComponentRef.value &&
typeof fieldComponentRef.value.focus === 'function' &&
document.activeElement !== fieldComponentRef.value // 检查当前是否有元素被聚焦
) {
fieldComponentRef.value.focus();
}
};
const fieldComponent = computed(() => {
const finalComponent = isString(component)
Expand Down Expand Up @@ -156,6 +166,18 @@ const computedProps = computed(() => {
};
});
watch(
() => computedProps.value?.autofocus,
(value) => {
if (value === true) {
nextTick(() => {
focus();
});
}
},
{ immediate: true },
);
const shouldDisabled = computed(() => {
return isDisabled.value || disabled || computedProps.value?.disabled;
});
Expand Down Expand Up @@ -275,6 +297,7 @@ function createComponentProps(slotProps: Record<string, any>) {
>
<component
:is="fieldComponent"
ref="fieldComponentRef"
:class="{
'border-destructive focus:border-destructive hover:border-destructive/80 focus:shadow-[0_0_0_2px_rgba(255,38,5,0.06)]':
isInValid,
Expand Down

0 comments on commit 64428b9

Please sign in to comment.