typescript vue 中的打字稿 - 类型 'Vue | 中不存在属性'validate' 元素 | Vue[] | 元素[]'。

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52109471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:37:30  来源:igfitidea点击:

Typescript in vue - Property 'validate' does not exist on type 'Vue | Element | Vue[] | Element[]'.

typescriptvue.jsvuetify.js

提问by Sam

I created v-formlike this

我是v-form这样创建的

<v-form ref="form" v-model="valid" lazy-validation>
  ...
  <v-btn
     :disabled="!valid"
     @click="submit"
   >
     submit
   </v-btn>
</v-form>

script:

脚本:

if (this.$refs.form.validate()) // Error is in here

If i just console.log(this.$ref.form)the validate() function is available. But why this error is coming while building?

如果我只是console.log(this.$ref.form)validate() 函数可用。但是为什么在构建时会出现这个错误?

回答by Ricky

Solutions:

解决方案:

Simple:

简单的:

(this.$refs.form as Vue & { validate: () => boolean }).validate()

Alternative (use this if you reference this.$refs.formmultiple times in your component):

替代方案(如果您this.$refs.form在组件中多次引用,请使用此选项)

computed: {
  form(): Vue & { validate: () => boolean } {
    return this.$refs.form as Vue & { validate: () => boolean }
  }
} // Use it like so: this.form.validate()

Reusable (use this if you use the v-formcomponent multiple times across your application):

可重用(如果您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
  }
}


Explanation:

解释:

In the Vuetemplate syntax, we can use the refattribute on a Vueinstance or a DOM element. If refis used in a v-forloop, an array of Vueinstances or DOM elements is retreived.

Vue模板语法中,我们可以refVue实例或 DOM 元素上使用属性。如果refv-for循环中使用,Vue则检索实例或 DOM 元素的数组。

This is why this.$refscan either return Vue | Element | Vue[] | Element[].

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

In order for TypeScriptto know which type is being used, we need to cast the value.

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

We can either do:

我们可以这样做:

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

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

We cast it to Vuebecause v-formis a Vueinstance (component) and not an Element.

我们将它转​​换为Vue因为v-form是一个Vue实例(组件)而不是一个Element.

My personal preference is to create a computed property which returns the Vueinstance(s) or DOM element(s) already casted.

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

ie.

IE。

computed: {
  form(): Vue {
    return this.$refs.form as Vue
  }
}


The v-forminstance has a validatemethod that returns a boolean, so we need to use an intersection type literal:

v-form实例有一个validate返回布尔值的方法,因此我们需要使用交集类型文字:

computed: {
  form(): Vue & { validate: () => boolean } {
    return this.$refs.form as Vue & { validate: () => boolean }
  }
}

Then we can use it like so: this.form.validate()

然后我们可以像这样使用它: this.form.validate()



A better solution would be to create a type with the intersection so that it can be reused across multiple components.

更好的解决方案是创建一个具有交集的类型,以便它可以在多个组件之间重用。

export type VForm = Vue & { validate: () => boolean }

Then import it in the component:

然后在组件中导入:

computed: {
  form(): VForm {
    return this.$refs.form as VForm
  }
}

回答by wuyuchao

let form: any = this.$refs.form
if(form.validate){}

回答by Ralph Gliane

Couldn't comment on the accepted solution since I'm new to StackOverflow and wanted to provide my solution to this. I took the same initial step to investigate as OP and did a console.log(this.$ref.form), the output on the console is actually an array of [VueComponent] and validate()function doesn't exist in that context.

无法对已接受的解决方案发表评论,因为我是 StackOverflow 的新手并想为此提供我的解决方案。我采取了与 OP 相同的初始步骤进行调查并做了一个console.log(this.$ref.form),控制台上的输出实际上是一个 [VueComponent] 数组,并且validate()该上下文中不存在函数。

I was able to access the validate()function on the form by doing this.$ref.form[0].validate()

我能够validate()通过执行访问表单上的功能this.$ref.form[0].validate()

回答by lastlink

None of the answers did it. I was trying to get the validate then promise to work on a form.

没有一个答案做到了。我试图获得验证然后承诺在表单上工作。

As per comment

根据评论

if you are building your vue component in typescript using

如果您正在使用打字稿构建 vue 组件

export default Vue.extend({})

then do

然后做

import { ValidationObserver, ValidationProvider, extend } from "vee-validate";
import { required } from "vee-validate/dist/rules";
import Vue, { VueConstructor } from "vue";
export default (Vue as VueConstructor<
  Vue & {
    $refs: {
      form: InstanceType<typeof ValidationProvider>;
    };
  }
>).extend({
  methods: {
    saveEntity() {
      if (this.loading) return;
      console.log(this.entity);
      this.$refs.form.validate().then(success => {
        if (!success) {
          console.log("not valid");
          return;
        }
        console.log("valid");
      });
    }
  }
})

This validates the ValidationObserver ref="form" just fine.

这验证了 ValidationObserver ref="form" 就好了。