illcrx
illcrx

Reputation: 814

Vue getters and setters on v-model:

I have a form that has about 30 fields on it and I would like to do some validations using getters and setters, but you use them in computed and cannot have computed and data values with the same name.

There have been examples where the model and the computed property are the same and the setters set the data model, but this is only with one field as an example. In practice for me to do this would be a decent refactor. Is there a way to maintain my model to data connection and use getters/setters?

Form- using the library Vue-Form-Generator

<form action="#">
  <vue-form-generator
    :schema="schema"
    :model="model"
    options="formOptions"
  >
  </vue-form-generator>
</form>

The data property:

 data: function () {
  return {
    model:{
        id: "",
        strategyId: Number, 
        name: "",
        symbol: "", 
        symbolPair: "",
        entryType: "", 
        conditionalLongEntryPoint: Number, 
        conditionalShortEntryPoint: Number, 
        entryPrice: Number, 
   ....

Upvotes: 0

Views: 1878

Answers (1)

JakeHamTexas
JakeHamTexas

Reputation: 51

https://v2.vuejs.org/v2/guide/forms.html#Modifiers

If you only need validation on whether the user supplies a number in a field where input type="number", this may be what you're looking for.

If you need anything more than that, I would suggest that you set a watch property on the member of data that you v-model onto and do your validation in that function. For this, you might perform a regex match on the data member that you're inspecting for validity.

What you appear to be asking for is the ability to have getters and setters on a member of data, which is not available out of the box. The closest thing to it would be applying conditional logic for when get and set methods are called, which would be a part of the methods object in your Vue component or root instance.

Upvotes: 1

Related Questions