SForm2.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. const n = `<template>
  2. <div class="s-form">
  3. <a-form
  4. :labelCol="colSpan.labelCol"
  5. :model="model"
  6. :rules="rules"
  7. :layout="layout"
  8. v-bind="safeAttrs"
  9. ref="form"
  10. :style="{
  11. display: 'grid',
  12. gridTemplateColumns: \`repeat(\${col}, 1fr)\`,
  13. gap: '20px'
  14. }"
  15. >
  16. <slot />
  17. </a-form>
  18. </div>
  19. </template>
  20. <script setup>
  21. import { ref, computed, watchEffect, useAttrs } from 'vue'
  22. const attrs = useAttrs()
  23. const props = defineProps({
  24. // 表单数据对象
  25. model: {
  26. type: Object,
  27. default() {
  28. return {}
  29. }
  30. },
  31. // 校验规则
  32. rules: {
  33. type: Object,
  34. default() {
  35. return {}
  36. }
  37. },
  38. // 排列方向:horizontal / vertical
  39. layout: {
  40. type: String,
  41. default() {
  42. return 'vertical'
  43. }
  44. },
  45. // 每行列数
  46. column: {
  47. type: [Number, String],
  48. default() {
  49. return 1
  50. }
  51. },
  52. // 标签宽度,单位 px
  53. labelWidth: {
  54. type: [Number, String],
  55. default() {
  56. return 80
  57. }
  58. }
  59. })
  60. const form = ref()
  61. const col = ref(props.column >= 5 ? 4 : props.column)
  62. /**
  63. * attrs 归一化(防御层):业务模板里 Boolean 属性的写法千奇百怪,任何非布尔值
  64. * 透传到 antd 声明为 \`Boolean\` 的 prop 都会刷
  65. * \`[Vue warn]: Invalid prop: type check failed for prop "disabled". Expected Boolean, got ...\`。
  66. *
  67. * 真实踩过的两种来源:
  68. * 1. Vue2 迁 Vue3 后模板里裸写的 Boolean 属性(\`disabled\` / \`allowClear\` …)被编译成 \`attr:""\`,
  69. * 一路透传到 antd 控件 —— 空串归一为 true。
  70. * 2. 业务侧写了 \`:disabled="cond && obj.someId"\` 这类表达式,\`&&\` 会返回**右操作数本身**
  71. * (如 \`"7b44c699bf8143aba01d62855d0fe38b"\`)而不是布尔值 —— 任何非布尔值统一转布尔。
  72. *
  73. * 归一化规则(语义与业务本意一致):
  74. * - "" → true(裸写属性,本意就是开启)
  75. * - "false" / "0" → false
  76. * - 其他字符串 → true(字符串只可能是 id / 任意真值,语义上都是"开启")
  77. * - number → Boolean(number)
  78. * - null/undefined→ 原样透传(由 Vue 走默认值)
  79. * 非 Boolean 类别的 attrs 一律不干预。
  80. */
  81. const BOOL_ATTRS = new Set([
  82. 'disabled',
  83. 'allowClear',
  84. 'clearable',
  85. 'showSearch',
  86. 'multiple',
  87. 'readonly',
  88. 'autofocus',
  89. 'bordered',
  90. 'checked',
  91. 'open',
  92. 'autoClearSearchValue',
  93. 'noDrag',
  94. 'isManual',
  95. 'expandAll',
  96. 'recursionChildren',
  97. 'treeCheckable',
  98. 'showOnlyOrganization',
  99. 'isDataScopeFilter'
  100. ])
  101. const toBool = (val) => {
  102. if (typeof val === 'boolean') return val
  103. if (val === '' || val === null || val === undefined) return val === '' ? true : val
  104. if (typeof val === 'string') return !(val === 'false' || val === '0')
  105. return Boolean(val)
  106. }
  107. const safeAttrs = computed(() => {
  108. const out = {}
  109. Object.keys(attrs || {}).forEach((key) => {
  110. const val = attrs[key]
  111. out[key] = BOOL_ATTRS.has(key) ? toBool(val) : val
  112. })
  113. return out
  114. })
  115. const colSpan = computed(() => {
  116. const layout = props.layout
  117. const width = props?.labelWidth + ''
  118. return layout === 'horizontal'
  119. ? {
  120. style: {
  121. width: width.includes('px') ? width : width + 'px'
  122. }
  123. }
  124. : {}
  125. })
  126. watchEffect(() => {
  127. if (props.column > 4) {
  128. console.warn(\`当前设置表单列column【\${props.column}】最多显示为4列,已默认为最多4列\`)
  129. }
  130. })
  131. /**
  132. * 校验。两种调用形态都支持:
  133. * 1. Promise 式:\`validate().then(...)\` / \`validate(['a','b']).then(...)\`(只校验部分字段)
  134. * 2. antd 回调式:\`validate((valid, err) => {...})\` / \`validate(['a'], cb)\`
  135. * —— vue2 项目迁过来的表单全是这种写法,不兼容会静默不保存。
  136. * 回调式不向外抛 reject(调用方没接 Promise,抛了就是 unhandled rejection)。
  137. * @param {Array|Function} [nameList] 只校验指定字段;或直接传回调
  138. * @param {Function} [callback] 回调 (valid, error)
  139. */
  140. const validate = (nameList, callback) => {
  141. const cb =
  142. typeof nameList === 'function' ? nameList : typeof callback === 'function' ? callback : null
  143. const list = typeof nameList === 'function' ? undefined : nameList
  144. return new Promise((resolve, reject) => {
  145. const runner = list && list.length ? form.value.validateFields(list) : form.value.validate()
  146. runner
  147. .then((form) => {
  148. if (cb) cb(true)
  149. resolve(form)
  150. })
  151. .catch((err) => {
  152. if (cb) {
  153. cb(false, err)
  154. resolve(undefined)
  155. return
  156. }
  157. reject(err)
  158. })
  159. })
  160. }
  161. /**
  162. * 单字段校验(透传 a-form.validateFields 的单字段形态),
  163. * 业务里 \`this.$refs.form.validateField('xxx')\` 依赖它。
  164. */
  165. const validateField = (name, callback) => {
  166. const cb = typeof callback === 'function' ? callback : null
  167. return new Promise((resolve, reject) => {
  168. if (!form.value) {
  169. resolve(undefined)
  170. return
  171. }
  172. form.value
  173. .validateFields(name)
  174. .then((v) => {
  175. if (cb) cb(true)
  176. resolve(v)
  177. })
  178. .catch((err) => {
  179. if (cb) {
  180. cb(false, err)
  181. resolve(undefined)
  182. return
  183. }
  184. reject(err)
  185. })
  186. })
  187. }
  188. /**
  189. * 清除校验结果。
  190. * 必须透传:SExtendFieldsForm 内部 <s-form ref="formRef"> 上调用 formRef.value.clearValidate(props),
  191. * 若 SForm 不暴露该方法,运行时会抛 "formRef.value.clearValidate is not a function"(Uncaught TypeError)。
  192. * 同时透传其余常用 a-form 实例方法,避免调用方再逐个报错。
  193. */
  194. const clearValidate = (name) => {
  195. form.value && form.value.clearValidate(name)
  196. }
  197. const resetFields = (name) => {
  198. form.value && form.value.resetFields(name)
  199. }
  200. const getFieldsValue = (nameList) => {
  201. return form.value ? form.value.getFieldsValue(nameList) : {}
  202. }
  203. const setFieldsValue = (values) => {
  204. form.value && form.value.setFieldsValue(values)
  205. }
  206. defineExpose({
  207. validate,
  208. validateField,
  209. clearValidate,
  210. resetFields,
  211. getFieldsValue,
  212. setFieldsValue
  213. })
  214. <\/script>
  215. <style lang="less" scoped>
  216. .s-form {
  217. width: 100%;
  218. .s-form-item {
  219. height: 100%;
  220. // 网格列是 1fr(minmax(auto,1fr)),子项 min-width 默认 auto 会被超长内容撑开整列,
  221. // 表现为输入框溢出弹窗/容器被裁切。归零后轨道可收缩到 1fr。
  222. min-width: 0;
  223. }
  224. }
  225. </style>
  226. `;
  227. export {
  228. n as default
  229. };