我创造了v-form
这样的
<v-form ref="form" v-model="valid" lazy-validation>
...
<v-btn
:disabled="!valid"
@click="submit"
>
submit
</v-btn>
</v-form>
脚本:
if (this.$refs.form.validate()) // Error is in here
如果我只是console.log(this.$ref.form)
validate()函数可用。但是,为什么在构建时会出现此错误?
简单:
(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
模板语法中,我们可以ref
在Vue
实例或DOM元素上使用属性。如果ref
在v-for
循环中使用if ,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
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句