element-plus/packages/hooks/use-form-item/index.ts
jeremywu 19bc41f965
feat(hooks): extracting size injection for form items (#3383)
* feat(hooks): extracting size injection for form items

- Extract common code for form items
- Apply extracted code for el-button

* - Address import order

* Update packages/hooks/use-form-item/index.ts

Co-authored-by: 三咲智子 <sxzz@sxzz.moe>

* - Fix type annotation for fallbacks

* - Use MaybeRef to mark type of local fallbacks

Co-authored-by: 三咲智子 <sxzz@sxzz.moe>
2021-09-13 23:14:48 +08:00

55 lines
1.5 KiB
TypeScript

import { inject, computed, getCurrentInstance, unref } from 'vue'
import { elFormKey, elFormItemKey } from '@element-plus/tokens'
import { buildProp } from '@element-plus/utils/props'
import { useGlobalConfig } from '@element-plus/utils/util'
import type { ExtractPropTypes } from 'vue'
import type { MaybeRef } from '@vueuse/shared'
const sizes = ['', 'large', 'medium', 'small', 'mini'] as const
export const useFormItemProps = {
size: buildProp({
type: String,
values: sizes,
default: '',
} as const),
disabled: Boolean,
} as const
export type UseFormItemProps = ExtractPropTypes<typeof useFormItemProps>
export type LocalFallbacks = {
size?: MaybeRef<UseFormItemProps['size'] | undefined>
disabled?: MaybeRef<UseFormItemProps['disabled'] | undefined>
}
export const useFormItem = ({ size, disabled }: LocalFallbacks) => {
const vm = getCurrentInstance()
const $ELEMENT = useGlobalConfig()
// vm.props is not reactive so we use the reactive one here.
const props = vm.proxy.$props as UseFormItemProps
const form = inject(elFormKey, undefined)
const formItem = inject(elFormItemKey, undefined)
return {
size: computed(() => {
// TODO, fallback to default size like 'medium/large' instead of empty string
return (
props.size ||
unref(size) ||
formItem?.size ||
form?.size ||
$ELEMENT.size ||
''
)
}),
disabled: computed(() => {
return (
props.disabled === true || unref(disabled) || form?.disabled || false
)
}),
}
}