I created v-form
like this
<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?
Solutions:
Simple:
Alternative (use this if you reference
this.$refs.form
multiple times in your component):Reusable (use this if you use the
v-form
component multiple times across your application):Explanation:
In the
Vue
template syntax, we can use theref
attribute on aVue
instance or a DOM element. Ifref
is used in av-for
loop, an array ofVue
instances or DOM elements is retreived.This is why
this.$refs
can either returnVue | Element | Vue[] | Element[]
.In order for
TypeScript
to know which type is being used, we need to cast the value.We can either do:
(this.$refs.form as Vue).validate()
or(<Vue>this.$refs.form).validate()
We cast it to
Vue
becausev-form
is aVue
instance (component) and not anElement
.My personal preference is to create a computed property which returns the
Vue
instance(s) or DOM element(s) already casted.ie.
The
v-form
instance has avalidate
method that returns a boolean, so we need to use an intersection type literal:Then we can use it like so:
this.form.validate()
A better solution would be to create a type with the intersection so that it can be reused across multiple components.
Then import it in the component:
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] andvalidate()
function doesn't exist in that context.I was able to access the
validate()
function on the form by doingthis.$ref.form[0].validate()
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
then do
This validates the ValidationObserver ref="form" just fine.