Component Hooks 组件相关
概述
Component Hooks 提供组件级别的工具函数,主要用于表单处理、页面上下文管理等。
导入方式
import { useFormItem, useFormItemSingle, usePageContext } from '@/hooks/component';1. useFormItem 表单项处理
处理表单组件的双向绑定、验证等逻辑。
类型定义
function useRuleFormItem<T extends Recordable, K extends keyof T, V = UnwrapRef<T[K]>>(
props: T,
key?: K,
changeEvent?: string,
emitData?: Ref<any[] | undefined>
): [
WritableComputedRef<V>, // state - 响应式状态
(val: V) => void, // setState - 设置状态
DeepReadonly<V>, // defaultState - 默认状态
FormItemContext // formItemContext - 表单项上下文
]基础用法
<template>
<a-input
:value="state"
@input="handleChange"
@blur="handleBlur"
/>
</template>
<script setup lang="ts">
import { useFormItem } from '@/hooks/component';
interface Props {
value?: string;
modelValue?: string;
}
const props = withDefaults(defineProps<Props>(), {
value: '',
});
const emit = defineEmits(['update:value', 'change', 'blur']);
// 使用 useFormItem 处理表单项
const [state, setState, defaultState, formItemContext] = useFormItem(
props,
'value', // 属性名
'change', // 触发事件
);
const handleChange = (e: Event) => {
const value = (e.target as HTMLInputElement).value;
setState(value);
};
const handleBlur = () => {
formItemContext.onFieldBlur();
};
</script>自定义表单组件
<template>
<div class="custom-input">
<label v-if="label">{{ label }}</label>
<a-input
:value="state"
:placeholder="placeholder"
@input="handleInput"
@blur="handleBlur"
/>
</div>
</template>
<script setup lang="ts">
import { useFormItem } from '@/hooks/component';
interface Props {
value?: string;
label?: string;
placeholder?: string;
}
const props = withDefaults(defineProps<Props>(), {
value: '',
placeholder: '请输入',
});
const emit = defineEmits(['update:value', 'change', 'blur']);
const [state, setState, defaultState, formItemContext] = useFormItem(props, 'value', 'change');
const handleInput = (e: Event) => {
const value = (e.target as HTMLInputElement).value;
setState(value);
};
const handleBlur = () => {
formItemContext.onFieldBlur();
};
</script>
<style scoped>
.custom-input {
display: flex;
flex-direction: column;
gap: 4px;
}
.custom-input label {
font-size: 14px;
color: rgba(0, 0, 0, 0.85);
}
</style>多选组件
<template>
<a-select
:value="state"
mode="multiple"
:options="options"
@change="handleChange"
/>
</template>
<script setup lang="ts">
import { useFormItem } from '@/hooks/component';
interface Props {
value?: string[];
options?: Array<{ label: string; value: string }>;
}
const props = withDefaults(defineProps<Props>(), {
value: () => [],
options: () => [],
});
const emit = defineEmits(['update:value', 'change']);
const [state, setState] = useFormItem(props, 'value', 'change');
const handleChange = (value: string[]) => {
setState(value);
};
</script>数字输入组件
<template>
<a-input-number
:value="state"
:min="min"
:max="max"
:step="step"
@change="handleChange"
/>
</template>
<script setup lang="ts">
import { useFormItem } from '@/hooks/component';
interface Props {
value?: number;
min?: number;
max?: number;
step?: number;
}
const props = withDefaults(defineProps<Props>(), {
value: 0,
min: -Infinity,
max: Infinity,
step: 1,
});
const emit = defineEmits(['update:value', 'change']);
const [state, setState] = useFormItem(props, 'value', 'change');
const handleChange = (value: number | null) => {
setState(value ?? 0);
};
</script>2. useFormItemSingle 单值表单项
处理单个值的表单项(不同于 useFormItem)。
使用示例
<template>
<div class="single-input">
<input
type="text"
:value="value"
@input="handleInput"
/>
</div>
</template>
<script setup lang="ts">
import { useFormItemSingle } from '@/hooks/component';
interface Props {
modelValue?: string;
}
const props = withDefaults(defineProps<Props>(), {
modelValue: '',
});
const emit = defineEmits(['update:modelValue']);
const { value, setValue } = useFormItemSingle(props, 'modelValue');
const handleInput = (e: Event) => {
setValue((e.target as HTMLInputElement).value);
};
</script>3. usePageContext 页面上下文
获取和设置页面级别的上下文信息。
使用示例
<template>
<div class="page-context-demo">
<p>页面标题: {{ context.title }}</p>
<p>页面类型: {{ context.pageType }}</p>
<a-button @click="updateContext">更新上下文</a-button>
</div>
</template>
<script setup lang="ts">
import { usePageContext } from '@/hooks/component';
const { context, setContext, getContext } = usePageContext();
// 获取上下文
console.log('当前上下文:', getContext());
// 更新上下文
const updateContext = () => {
setContext({
title: '新页面标题',
pageType: 'detail',
meta: {
isEdit: true,
},
});
};
</script>在表单页面使用
<template>
<div class="form-page">
<a-page-header :title="context.title" @back="handleBack" />
<BasicForm
:schemas="formSchemas"
@register="registerForm"
@submit="handleSubmit"
/>
</div>
</template>
<script setup lang="ts">
import { usePageContext } from '@/hooks/component';
import { useForm } from '@/hooks/component';
import { useRoute, useRouter } from 'vue-router';
const route = useRoute();
const router = useRouter();
const { context, setContext } = usePageContext();
// 设置页面上下文
onMounted(() => {
const isEdit = route.query.id !== undefined;
setContext({
title: isEdit ? '编辑用户' : '新建用户',
pageType: isEdit ? 'edit' : 'create',
recordId: route.query.id,
});
});
const [registerForm, { getFieldsValue, setFieldsValue }] = useForm();
// 如果是编辑模式,加载数据
watch(() => context.recordId, async (id) => {
if (id) {
const data = await api.getUserDetail(id);
setFieldsValue(data);
}
});
const handleSubmit = async (values: any) => {
if (context.pageType === 'edit') {
await api.updateUser(context.recordId, values);
} else {
await api.createUser(values);
}
router.back();
};
const handleBack = () => {
router.back();
};
</script>完整示例:自定义选择组件
<template>
<div class="custom-select">
<label v-if="label" class="custom-select-label">{{ label }}</label>
<a-select
v-bind="$attrs"
:value="state"
:mode="mode"
:disabled="disabled"
:placeholder="placeholder"
:options="computedOptions"
@change="handleChange"
@blur="handleBlur"
@focus="handleFocus"
>
<template #notFoundContent>
<a-empty :image="Empty.PRESENTED_IMAGE_SIMPLE" description="暂无数据" />
</template>
</a-select>
<div v-if="hint" class="custom-select-hint">{{ hint }}</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue';
import { useFormItem } from '@/hooks/component';
import { Empty } from 'ant-design-vue';
interface Props {
value?: any;
label?: string;
mode?: 'multiple' | 'tags' | 'combobox';
disabled?: boolean;
placeholder?: string;
options?: Array<{ label: string; value: any; disabled?: boolean }>;
hint?: string;
}
const props = withDefaults(defineProps<Props>(), {
value: undefined,
mode: undefined,
disabled: false,
placeholder: '请选择',
options: () => [],
});
const emit = defineEmits(['update:value', 'change', 'blur', 'focus']);
// 使用 useFormItem 处理表单项逻辑
const [state, setState, defaultState, formItemContext] = useFormItem(
props,
'value',
'change'
);
// 计算属性
const computedOptions = computed(() => {
return props.options.map(option => ({
...option,
disabled: option.disabled || props.disabled,
}));
});
// 事件处理
const handleChange = (value: any) => {
setState(value);
};
const handleBlur = () => {
formItemContext.onFieldBlur();
emit('blur');
};
const handleFocus = () => {
emit('focus');
};
</script>
<style scoped>
.custom-select {
display: flex;
flex-direction: column;
gap: 4px;
}
.custom-select-label {
font-size: 14px;
color: rgba(0, 0, 0, 0.85);
font-weight: 500;
}
.custom-select-hint {
font-size: 12px;
color: rgba(0, 0, 0, 0.45);
margin-top: 2px;
}
</style>完整示例:自定义开关组件
<template>
<div class="custom-switch">
<label v-if="label" class="custom-switch-label">{{ label }}</label>
<a-switch
v-bind="$attrs"
:checked="state"
:disabled="disabled"
:loading="loading"
:checked-children="checkedChildren"
:un-checked-children="unCheckedChildren"
@change="handleChange"
/>
<span v-if="showStatus" class="custom-switch-status">
{{ state ? activeText : inactiveText }}
</span>
<div v-if="hint" class="custom-switch-hint">{{ hint }}</div>
</div>
</template>
<script setup lang="ts">
import { useFormItem } from '@/hooks/component';
interface Props {
value?: boolean;
label?: string;
disabled?: boolean;
loading?: boolean;
checkedChildren?: string;
unCheckedChildren?: string;
activeText?: string;
inactiveText?: string;
showStatus?: boolean;
hint?: string;
}
const props = withDefaults(defineProps<Props>(), {
value: false,
disabled: false,
loading: false,
checkedChildren: '开',
unCheckedChildren: '关',
activeText: '已启用',
inactiveText: '已禁用',
showStatus: false,
});
const emit = defineEmits(['update:value', 'change']);
const [state, setState, defaultState, formItemContext] = useFormItem(
props,
'value',
'change'
);
const handleChange = (checked: boolean) => {
setState(checked);
};
</script>
<style scoped>
.custom-switch {
display: flex;
align-items: center;
gap: 8px;
}
.custom-switch-label {
font-size: 14px;
color: rgba(0, 0, 0, 0.85);
}
.custom-switch-status {
font-size: 12px;
color: rgba(0, 0, 0, 0.45);
}
.custom-switch-hint {
font-size: 12px;
color: rgba(0, 0, 0, 0.45);
margin-top: 2px;
}
</style>最佳实践
1. 组件设计原则
// ✅ 好的做法:使用 useFormItem 处理双向绑定
const [state, setState] = useFormItem(props, 'value', 'change');
// ❌ 不好的做法:手动处理
const localValue = ref(props.value);
watch(localValue, (val) => {
emit('update:value', val);
});2. 表单验证集成
<script setup lang="ts">
import { useFormItem } from '@/hooks/component';
const [state, setState, defaultState, formItemContext] = useFormItem(props);
// 触发验证
const validate = () => {
return formItemContext.onFieldChange();
};
// 清除验证
const clearValidate = () => {
formItemContext?.clearValidate();
};
</script>3. 类型安全
interface CustomInputProps {
value?: string;
maxLength?: number;
disabled?: boolean;
}
const props = withDefaults(defineProps<CustomInputProps>(), {
value: '',
maxLength: 100,
disabled: false,
});
const [state] = useFormItem(props, 'value', 'change');
// state 自动推断为 WritableComputedRef<string>注意事项
- 双向绑定:始终使用
useFormItem处理表单组件的双向绑定 - 事件触发:使用
setState会自动触发 change 事件和表单验证 - 默认值:
defaultState是只读的,用于比较值是否变化 - 表单集成:
formItemContext提供了与 Ant Design Vue Form 的集成 - 空值处理:Hook 内部已处理空值(null/undefined/'')的情况
相关文档
- [BasicForm 组件](../../11. 组件库文档/02. 表单组件/BasicForm.md)
- Ant Design Vue Form
- [Core Hooks](../02. CoreHooks/coreHooks.md)
文档版本: 1.0.0 最后更新: 2026-01-10