Form.vue 9.0 KB

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