element封装了各类组件,有些组件隐藏的比较深,并一定能找到其对象类型,比如el-form,已经表单中的rules等,这里简单记录一下如何引用。
types目录下,新建element-plus.ts,专门存放element组件的类型结构
import { ElForm } from 'element-plus'
import { FormItemRule } from 'element-plus/es/tokens/form'
export type IElForm = InstanceType<typeof ElForm>
export type IFormRule = Record<string, FormItemRule[]>
在vue组件中再引入包。
import type { IElForm, IFormRule } from '@/types/element-plus'
import { InternalRuleItem } from 'async-validator/dist-types/interface'
获取elform和rules的引用
const loginFormRef = ref<IElForm | null>(null)
const loginRules = ref<IFormRule>({
username: [{
validator: validateName,
trigger: 'blur'
}],
password: [{
validator: validatePass,
trigger: 'blur'
}]
}
)
const validateName = (rule: InternalRuleItem, value: string, callback: (error?: string | Error) => void) =>{
if (/^\d+$/.test(value)) callback(new Error('用户名不能全为数字'))
else {
if (value && UserName.test(value)) {
callback()
} else {
callback(new Error('用户名不符合规范'))
}
}
}