想加一个全局表单的检验功能,每个 input 上面加又太麻烦 随便写一个方法
import { computed, reactive, watch } from "vue";
export function createForm<T>(obj: T): T {
let o:any = reactive(obj as any);
watch(o, () => {
Reflect.ownKeys(o).forEach((k) => {
let value = Reflect.get(o, k);
if (value && typeof value === "string") {
Reflect.set(o, k, value.toString().replace(/[^\w]/g, ""));
}
});
});
return o as T;
}
使用方法,在每次创建表单的时候调用这个函数,并创建一个 reactive 对象
<template></tempalte>
<script lang="ts" setup>
...
interface FormState{
password: string;
confirmPassword: string;
email: string;
}
const formState = createForm<FormState>({
password: "",
confirmPassword: "",
email: "",
});
...
</script>
|