vue 中的打字稿-“Vue \| 类型”上不存在属性“验证”元素 \| 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() 函数可用。但是为什么在构建时会出现这个错误?

原文由 Sam 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 427
2 个回答

解决方案:

简单的:

 (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 属性。如果在 ref v-for 循环中使用 --- ,则会检索 Vue 实例或 DOM 元素的数组。

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

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

我们可以这样做:

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

We cast it to Vue because v-form is a Vue instance (component) and not an Element .

我个人的偏好是创建一个计算属性,该属性返回 Vue 实例或已转换的 DOM 元素。

IE。

 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
  }
}

原文由 Ricky 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果你使用 vue-class-componentvue-property-decorator 你可以这样做:

types.ts 中定义一个具有 vuetify 表单功能的新类型:

 export type VForm = Vue & {
  validate: () => boolean;
  resetValidation: () => boolean;
  reset: () => void;
};

然后导入您的组件:

 import { VForm } from "types";
import { Component, Ref} from "vue-property-decorator";

在组件中使用 @Ref 来定义表单:

 export default class YourComponent extends Vue {
  @Ref("form") readonly form!: VForm;
}

所以在你的方法中你可以像这样使用它:

 this.form.validate();
this.form.resetValidation();
this.form.reset();

原文由 R3dNag 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题