1. 问题
我们项目使用的是ant-design-vue
这个UI框架, 用到了form表单的功能, 写法如下:
this.$refs.ruleForm.validate(...)
本地编译报了如下的错误:
Property 'validate' does not exist on type 'Vue | Element | Vue[] | Element[]'.
Property 'validate' does not exist on type 'Vue'.
2. 分析
意思大致是validate()
并不是Vue
的方法,它只是你某个组件的方法。所以你需要把 this.$refs.ruleForm
显式标注为那个组件类型
this.$ref
可能会返回一个vue对象或者是Element对象,但是typescript并不知道这是个什么
所以, 我们需要给TS加上类型断言,告诉它是什么
3. 简单的解决方法
// const ruleForm = this.$refs.ruleForm as any
// 或者:
const ruleForm: any = this.$refs.ruleForm
ruleForm.validate((valid: boolean) => {
if (valid) {
//
} else {
console.log('error submit!!')
return false
}
})
也可以直接写
(this.$refs['ruleForm'] as any).validate((valid: boolean) => {
if (valid) {
//
} else {
console.log('error submit!!')
return false
}
})