| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239 |
- const n = `<template>
- <div class="s-form">
- <a-form
- :labelCol="colSpan.labelCol"
- :model="model"
- :rules="rules"
- :layout="layout"
- v-bind="safeAttrs"
- ref="form"
- :style="{
- display: 'grid',
- gridTemplateColumns: \`repeat(\${col}, 1fr)\`,
- gap: '20px'
- }"
- >
- <slot />
- </a-form>
- </div>
- </template>
- <script setup>
- import { ref, computed, watchEffect, useAttrs } from 'vue'
- const attrs = useAttrs()
- const props = defineProps({
- // 表单数据对象
- model: {
- type: Object,
- default() {
- return {}
- }
- },
- // 校验规则
- rules: {
- type: Object,
- default() {
- return {}
- }
- },
- // 排列方向:horizontal / vertical
- layout: {
- type: String,
- default() {
- return 'vertical'
- }
- },
- // 每行列数
- column: {
- type: [Number, String],
- default() {
- return 1
- }
- },
- // 标签宽度,单位 px
- labelWidth: {
- type: [Number, String],
- default() {
- return 80
- }
- }
- })
- const form = ref()
- const col = ref(props.column >= 5 ? 4 : props.column)
- /**
- * attrs 归一化(防御层):业务模板里 Boolean 属性的写法千奇百怪,任何非布尔值
- * 透传到 antd 声明为 \`Boolean\` 的 prop 都会刷
- * \`[Vue warn]: Invalid prop: type check failed for prop "disabled". Expected Boolean, got ...\`。
- *
- * 真实踩过的两种来源:
- * 1. Vue2 迁 Vue3 后模板里裸写的 Boolean 属性(\`disabled\` / \`allowClear\` …)被编译成 \`attr:""\`,
- * 一路透传到 antd 控件 —— 空串归一为 true。
- * 2. 业务侧写了 \`:disabled="cond && obj.someId"\` 这类表达式,\`&&\` 会返回**右操作数本身**
- * (如 \`"7b44c699bf8143aba01d62855d0fe38b"\`)而不是布尔值 —— 任何非布尔值统一转布尔。
- *
- * 归一化规则(语义与业务本意一致):
- * - "" → true(裸写属性,本意就是开启)
- * - "false" / "0" → false
- * - 其他字符串 → true(字符串只可能是 id / 任意真值,语义上都是"开启")
- * - number → Boolean(number)
- * - null/undefined→ 原样透传(由 Vue 走默认值)
- * 非 Boolean 类别的 attrs 一律不干预。
- */
- const BOOL_ATTRS = new Set([
- 'disabled',
- 'allowClear',
- 'clearable',
- 'showSearch',
- 'multiple',
- 'readonly',
- 'autofocus',
- 'bordered',
- 'checked',
- 'open',
- 'autoClearSearchValue',
- 'noDrag',
- 'isManual',
- 'expandAll',
- 'recursionChildren',
- 'treeCheckable',
- 'showOnlyOrganization',
- 'isDataScopeFilter'
- ])
- const toBool = (val) => {
- if (typeof val === 'boolean') return val
- if (val === '' || val === null || val === undefined) return val === '' ? true : val
- if (typeof val === 'string') return !(val === 'false' || val === '0')
- return Boolean(val)
- }
- const safeAttrs = computed(() => {
- const out = {}
- Object.keys(attrs || {}).forEach((key) => {
- const val = attrs[key]
- out[key] = BOOL_ATTRS.has(key) ? toBool(val) : val
- })
- return out
- })
- const colSpan = computed(() => {
- const layout = props.layout
- const width = props?.labelWidth + ''
- return layout === 'horizontal'
- ? {
- style: {
- width: width.includes('px') ? width : width + 'px'
- }
- }
- : {}
- })
- watchEffect(() => {
- if (props.column > 4) {
- console.warn(\`当前设置表单列column【\${props.column}】最多显示为4列,已默认为最多4列\`)
- }
- })
- /**
- * 校验。两种调用形态都支持:
- * 1. Promise 式:\`validate().then(...)\` / \`validate(['a','b']).then(...)\`(只校验部分字段)
- * 2. antd 回调式:\`validate((valid, err) => {...})\` / \`validate(['a'], cb)\`
- * —— vue2 项目迁过来的表单全是这种写法,不兼容会静默不保存。
- * 回调式不向外抛 reject(调用方没接 Promise,抛了就是 unhandled rejection)。
- * @param {Array|Function} [nameList] 只校验指定字段;或直接传回调
- * @param {Function} [callback] 回调 (valid, error)
- */
- const validate = (nameList, callback) => {
- const cb =
- typeof nameList === 'function' ? nameList : typeof callback === 'function' ? callback : null
- const list = typeof nameList === 'function' ? undefined : nameList
- return new Promise((resolve, reject) => {
- const runner = list && list.length ? form.value.validateFields(list) : form.value.validate()
- runner
- .then((form) => {
- if (cb) cb(true)
- resolve(form)
- })
- .catch((err) => {
- if (cb) {
- cb(false, err)
- resolve(undefined)
- return
- }
- reject(err)
- })
- })
- }
- /**
- * 单字段校验(透传 a-form.validateFields 的单字段形态),
- * 业务里 \`this.$refs.form.validateField('xxx')\` 依赖它。
- */
- const validateField = (name, callback) => {
- const cb = typeof callback === 'function' ? callback : null
- return new Promise((resolve, reject) => {
- if (!form.value) {
- resolve(undefined)
- return
- }
- form.value
- .validateFields(name)
- .then((v) => {
- if (cb) cb(true)
- resolve(v)
- })
- .catch((err) => {
- if (cb) {
- cb(false, err)
- resolve(undefined)
- return
- }
- reject(err)
- })
- })
- }
- /**
- * 清除校验结果。
- * 必须透传:SExtendFieldsForm 内部 <s-form ref="formRef"> 上调用 formRef.value.clearValidate(props),
- * 若 SForm 不暴露该方法,运行时会抛 "formRef.value.clearValidate is not a function"(Uncaught TypeError)。
- * 同时透传其余常用 a-form 实例方法,避免调用方再逐个报错。
- */
- const clearValidate = (name) => {
- form.value && form.value.clearValidate(name)
- }
- const resetFields = (name) => {
- form.value && form.value.resetFields(name)
- }
- const getFieldsValue = (nameList) => {
- return form.value ? form.value.getFieldsValue(nameList) : {}
- }
- const setFieldsValue = (values) => {
- form.value && form.value.setFieldsValue(values)
- }
- defineExpose({
- validate,
- validateField,
- clearValidate,
- resetFields,
- getFieldsValue,
- setFieldsValue
- })
- <\/script>
- <style lang="less" scoped>
- .s-form {
- width: 100%;
- .s-form-item {
- height: 100%;
- // 网格列是 1fr(minmax(auto,1fr)),子项 min-width 默认 auto 会被超长内容撑开整列,
- // 表现为输入框溢出弹窗/容器被裁切。归零后轨道可收缩到 1fr。
- min-width: 0;
- }
- }
- </style>
- `;
- export {
- n as default
- };
|