Form.vue 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. <script lang="tsx">
  2. import { PropType, defineComponent, ref, computed, unref, watch, onMounted } from 'vue'
  3. import { ElForm, ElFormItem, ElRow, ElCol, ElTooltip } from 'element-plus'
  4. import { componentMap } from './componentMap'
  5. import { propTypes } from '@/utils/propTypes'
  6. import { getSlot } from '@/utils/tsxHelper'
  7. import {
  8. setTextPlaceholder,
  9. setGridProp,
  10. setComponentProps,
  11. setItemComponentSlots,
  12. initModel,
  13. setFormItemSlots
  14. } from './helper'
  15. import { useRenderSelect } from './components/useRenderSelect'
  16. import { useRenderRadio } from './components/useRenderRadio'
  17. import { useRenderCheckbox } from './components/useRenderCheckbox'
  18. import { useDesign } from '@/hooks/web/useDesign'
  19. import { findIndex } from '@/utils'
  20. import { set } from 'lodash-es'
  21. import { FormProps } from './types'
  22. import { Icon } from '@/components/Icon'
  23. import { FormSchema, FormSetPropsType } from '@/types/form'
  24. const { getPrefixCls } = useDesign()
  25. const prefixCls = getPrefixCls('form')
  26. export default defineComponent({
  27. name: 'Form',
  28. props: {
  29. // 生成Form的布局结构数组
  30. schema: {
  31. type: Array as PropType<FormSchema[]>,
  32. default: () => []
  33. },
  34. // 是否需要栅格布局
  35. isCol: propTypes.bool.def(true),
  36. // 表单数据对象
  37. model: {
  38. type: Object as PropType<Recordable>,
  39. default: () => ({})
  40. },
  41. // 是否自动设置placeholder
  42. autoSetPlaceholder: propTypes.bool.def(true),
  43. // 是否自定义内容
  44. isCustom: propTypes.bool.def(false),
  45. // 表单label宽度
  46. labelWidth: propTypes.oneOfType([String, Number]).def('auto')
  47. },
  48. emits: ['register'],
  49. setup(props, { slots, expose, emit }) {
  50. // element form 实例
  51. const elFormRef = ref<ComponentRef<typeof ElForm>>()
  52. // useForm传入的props
  53. const outsideProps = ref<FormProps>({})
  54. const mergeProps = ref<FormProps>({})
  55. const getProps = computed(() => {
  56. const propsObj = { ...props }
  57. Object.assign(propsObj, unref(mergeProps))
  58. return propsObj
  59. })
  60. // 表单数据
  61. const formModel = ref<Recordable>({})
  62. onMounted(() => {
  63. emit('register', unref(elFormRef)?.$parent, unref(elFormRef))
  64. })
  65. // 对表单赋值
  66. const setValues = (data: Recordable = {}) => {
  67. formModel.value = Object.assign(unref(formModel), data)
  68. }
  69. const setProps = (props: FormProps = {}) => {
  70. mergeProps.value = Object.assign(unref(mergeProps), props)
  71. outsideProps.value = props
  72. }
  73. const delSchema = (field: string) => {
  74. const { schema } = unref(getProps)
  75. const index = findIndex(schema, (v: FormSchema) => v.field === field)
  76. if (index > -1) {
  77. schema.splice(index, 1)
  78. }
  79. }
  80. const addSchema = (formSchema: FormSchema, index?: number) => {
  81. const { schema } = unref(getProps)
  82. if (index !== void 0) {
  83. schema.splice(index, 0, formSchema)
  84. return
  85. }
  86. schema.push(formSchema)
  87. }
  88. const setSchema = (schemaProps: FormSetPropsType[]) => {
  89. const { schema } = unref(getProps)
  90. for (const v of schema) {
  91. for (const item of schemaProps) {
  92. if (v.field === item.field) {
  93. set(v, item.path, item.value)
  94. }
  95. }
  96. }
  97. }
  98. const getElFormRef = (): ComponentRef<typeof ElForm> => {
  99. return unref(elFormRef) as ComponentRef<typeof ElForm>
  100. }
  101. expose({
  102. setValues,
  103. formModel,
  104. setProps,
  105. delSchema,
  106. addSchema,
  107. setSchema,
  108. getElFormRef
  109. })
  110. // 监听表单结构化数组,重新生成formModel
  111. watch(
  112. () => unref(getProps).schema,
  113. (schema = []) => {
  114. formModel.value = initModel(schema, unref(formModel))
  115. },
  116. {
  117. immediate: true,
  118. deep: true
  119. }
  120. )
  121. // 渲染包裹标签,是否使用栅格布局
  122. const renderWrap = () => {
  123. const { isCol } = unref(getProps)
  124. const content = isCol ? (
  125. <ElRow gutter={20}>{renderFormItemWrap()}</ElRow>
  126. ) : (
  127. renderFormItemWrap()
  128. )
  129. return content
  130. }
  131. // 是否要渲染el-col
  132. const renderFormItemWrap = () => {
  133. // hidden属性表示隐藏,不做渲染
  134. const { schema = [], isCol } = unref(getProps)
  135. return schema
  136. .filter((v) => !v.hidden)
  137. .map((item) => {
  138. // 如果是 Divider 组件,需要自己占用一行
  139. const isDivider = item.component === 'Divider'
  140. const Com = componentMap['Divider'] as ReturnType<typeof defineComponent>
  141. return isDivider ? (
  142. <Com {...{ contentPosition: 'left', ...item.componentProps }}>{item?.label}</Com>
  143. ) : isCol ? (
  144. // 如果需要栅格,需要包裹 ElCol
  145. <ElCol {...setGridProp(item.colProps)}>{renderFormItem(item)}</ElCol>
  146. ) : (
  147. renderFormItem(item)
  148. )
  149. })
  150. }
  151. // 渲染formItem
  152. const renderFormItem = (item: FormSchema) => {
  153. // 单独给只有options属性的组件做判断
  154. const notRenderOptions = ['SelectV2', 'Cascader', 'Transfer']
  155. const slotsMap: Recordable = {
  156. ...setItemComponentSlots(slots, item?.componentProps?.slots, item.field)
  157. }
  158. if (
  159. item?.component !== 'SelectV2' &&
  160. item?.component !== 'Cascader' &&
  161. item?.componentProps?.options
  162. ) {
  163. slotsMap.default = () => renderOptions(item)
  164. }
  165. const formItemSlots: Recordable = setFormItemSlots(slots, item.field)
  166. // 如果有 labelMessage,自动使用插槽渲染
  167. if (item?.labelMessage) {
  168. formItemSlots.label = () => {
  169. return (
  170. <>
  171. <span>{item.label}</span>
  172. <ElTooltip placement="right" raw-content>
  173. {{
  174. content: () => <span v-html={item.labelMessage}></span>,
  175. default: () => (
  176. <Icon
  177. icon="ep:warning"
  178. size={16}
  179. color="var(--el-color-primary)"
  180. class="ml-2px relative top-1px"
  181. ></Icon>
  182. )
  183. }}
  184. </ElTooltip>
  185. </>
  186. )
  187. }
  188. }
  189. return (
  190. <ElFormItem {...(item.formItemProps || {})} prop={item.field} label={item.label || ''}>
  191. {{
  192. ...formItemSlots,
  193. default: () => {
  194. const Com = componentMap[item.component as string] as ReturnType<
  195. typeof defineComponent
  196. >
  197. const { autoSetPlaceholder } = unref(getProps)
  198. return slots[item.field] ? (
  199. getSlot(slots, item.field, formModel.value)
  200. ) : (
  201. <Com
  202. vModel={formModel.value[item.field]}
  203. {...(autoSetPlaceholder && setTextPlaceholder(item))}
  204. {...setComponentProps(item)}
  205. {...(notRenderOptions.includes(item?.component as string) &&
  206. item?.componentProps?.options
  207. ? { options: item?.componentProps?.options || [] }
  208. : {})}
  209. >
  210. {{ ...slotsMap }}
  211. </Com>
  212. )
  213. }
  214. }}
  215. </ElFormItem>
  216. )
  217. }
  218. // 渲染options
  219. const renderOptions = (item: FormSchema) => {
  220. switch (item.component) {
  221. case 'Select':
  222. const { renderSelectOptions } = useRenderSelect(slots)
  223. return renderSelectOptions(item)
  224. case 'Radio':
  225. case 'RadioButton':
  226. const { renderRadioOptions } = useRenderRadio()
  227. return renderRadioOptions(item)
  228. case 'Checkbox':
  229. case 'CheckboxButton':
  230. const { renderChcekboxOptions } = useRenderCheckbox()
  231. return renderChcekboxOptions(item)
  232. default:
  233. break
  234. }
  235. }
  236. // 过滤传入Form组件的属性
  237. const getFormBindValue = () => {
  238. // 避免在标签上出现多余的属性
  239. const delKeys = ['schema', 'isCol', 'autoSetPlaceholder', 'isCustom', 'model']
  240. const props = { ...unref(getProps) }
  241. for (const key in props) {
  242. if (delKeys.indexOf(key) !== -1) {
  243. delete props[key]
  244. }
  245. }
  246. return props
  247. }
  248. return () => (
  249. <ElForm
  250. ref={elFormRef}
  251. {...getFormBindValue()}
  252. model={props.isCustom ? props.model : formModel}
  253. class={prefixCls}
  254. >
  255. {{
  256. // 如果需要自定义,就什么都不渲染,而是提供默认插槽
  257. default: () => {
  258. const { isCustom } = unref(getProps)
  259. return isCustom ? getSlot(slots, 'default') : renderWrap()
  260. }
  261. }}
  262. </ElForm>
  263. )
  264. }
  265. })
  266. </script>
  267. <style lang="less" scoped>
  268. .@{elNamespace}-form.@{namespace}-form .@{elNamespace}-row {
  269. margin-right: 0 !important;
  270. margin-left: 0 !important;
  271. }
  272. </style>