javascriptvue.jsvuejs2

How do you find the element via it's binding in Vue


In Vue2 how would one find an element if the bound property is known?
Is there a way to associate the two?

<input ref="inputRef" v-model="model.name">

In this case it would be neat to be able to validate the model and then show an error on the input control without having to specify an identifier for each input.

It is possible to get the bound expression:

// expression = "model.name"
const expression = inputRef.$vnode.data.model.expression

However to resolve every possible expression and map it onto the property seems like overkill.

As far as I can see it's not possible to add metadata to a variable in order to display error messages or associate the input with a property.

Is there a surefire way to map from an instance of a variable to the element on which it is bound inside a form?


Solution

  • At the time of writing it is not possible to determine the bound property in any easy way.

    In Vue2 it was possible to get the bound expression and then resolve the name with some kind of matching, but that's a terrible idea and at that point it's easier to include a name manually.

    So, no, this can not be done in a reliable way and you have to include the name or some kind of metadata to accompany the binding.

    Vuelidate a validation framework that uses model validation solves this by binding the error in the UI manually.