Vue中的打字稿-类型'Vue |中没有属性'validate' 元素| Vue [] | 元件[]'。

山姆

我创造了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模板语法中,我们可以refVue实例或DOM元素使用属性如果refv-for循环中使用if Vue则检索实例或DOM元素的数组

这就是为什么this.$refs要么返回Vue | Element | Vue[] | Element[]

为了TypeScript知道正在使用哪种类型,我们需要强制转换值。

我们可以做:

(this.$refs.form as Vue).validate() 要么 (<Vue>this.$refs.form).validate()

我们将其强制转换为Vue因为v-formVue实例(组件)而不是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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章