解决方案:
简单:
(this.$refs.form as Vue & { validate: () => boolean }).validate()
替代(如果您在组件中多次引用this.$refs.form,请使用此选项):
computed: {
form(): Vue & { validate: () => boolean } {
return this.$refs.form as Vue & { validate: () => boolean }
}
} // Use it like so: this.form.validate()
可重用(如果您在应用程序中多次使用v-form 组件,请使用它):
// In a TS file
export type VForm = Vue & { validate: () => boolean }
// In component, import `VForm`
computed: {
form(): VForm {
return this.$refs.form as VForm
}
}
解释:
在Vue 模板语法中,我们可以在Vue 实例或DOM 元素上使用ref 属性。如果在v-for 循环中使用ref,则会检索Vue 实例或DOM 元素的数组。
这就是为什么this.$refs 可以返回Vue | Element | Vue[] | Element[]。
为了让TypeScript 知道正在使用哪种类型,我们需要转换值。
我们可以这样做:
(this.$refs.form as Vue).validate() 或 (<Vue>this.$refs.form).validate()
我们将其转换为Vue,因为v-form 是Vue 实例(组件)而不是Element。
我个人的偏好是创建一个计算属性,该属性返回已转换的 Vue 实例或 DOM 元素。
即。
computed: {
form(): Vue {
return this.$refs.form as Vue
}
}
v-form 实例有一个返回布尔值的validate 方法,因此我们需要使用交集类型文字:
computed: {
form(): Vue & { validate: () => boolean } {
return this.$refs.form as Vue & { validate: () => boolean }
}
}
那么我们可以这样使用它:this.form.validate()
更好的解决方案是创建一个具有交集的类型,以便可以跨多个组件重用它。
export type VForm = Vue & { validate: () => boolean }
然后在组件中导入:
computed: {
form(): VForm {
return this.$refs.form as VForm
}
}