yanzhen-design-vue
Version:
82 lines (81 loc) • 2.24 kB
JavaScript
import { ref, useSlots, useAttrs, computed, unref, h, mergeProps } from "vue";
import { Form } from "ant-design-vue";
import { pick, isFunction } from "lodash-es";
import { useProxyProps } from "@yanzhen-libs/utils-vue";
import { isEmptyValue } from "@yanzhen-libs/utils";
import { useInjectForm } from "ant-design-vue/es/form/context";
import { AntForm } from "./form.mjs";
import { useProvideForm } from "./hooks/use-form.mjs";
function useForm(props, emit) {
const _ref = ref(null);
const slots = useSlots();
const attrs = useAttrs();
const model = useInjectForm().model;
const modelRef = computed(() => props.model ?? unref(model) ?? {});
const rulesRef = computed(() => props.rules ?? {});
const { validate, resetFields, clearValidate, scrollToField } = useProvideForm(
modelRef,
rulesRef
);
const config = computed(() => {
return pick(props, ...Object.keys(AntForm.props));
});
const proxyProps = useProxyProps(config, AntForm.emits, {
emit,
exclude: ["onValidate"],
filter: true
});
const onValidate = (name, ...args) => {
validate(name).then((r) => r);
emit("validate", name, ...args);
};
const ctx = {
resetFields,
clearValidate,
scrollToField,
async validateFields(nameList) {
if (isEmptyValue(nameList)) {
return Promise.resolve();
}
await Promise.allSettled(nameList.map((name) => validate(name)));
}
};
const exposeCtx = new Proxy(ctx, {
get(target, p, receiver) {
const formRef = unref(_ref);
const fun1 = Reflect.get(target, p, receiver);
const fun2 = !isEmptyValue(formRef) ? Reflect.get(formRef, p, receiver) : null;
if (Object.keys(ctx).includes(p)) {
return (...args) => {
for (const fun of [fun1, fun2]) {
try {
isFunction(fun) && fun(...args);
} catch {
}
}
};
}
return fun1 ?? fun2;
}
});
return [
{
_ref,
proxyProps,
onValidate,
exposeCtx
},
(props2) => {
return h(
Form,
mergeProps(attrs, unref(proxyProps), props2, {
ref: _ref
}),
slots
);
}
];
}
export {
useForm
};