E
E
EA-EKB2018-02-21 19:48:14
Vue.js
EA-EKB, 2018-02-21 19:48:14

How to write your own v-model for each input from the set of inputs output via v-for?

I recently started learning Vue.js and ran into this problem. On the page, using v-for, a set of input type=file is displayed. Some of these inputs are required to be filled in, without filling them in, the button for moving to the next step is inactive. I came up with the following solution, which works great for input type=text, radio buttons and checkboxes, which are mostly rendered without v-for.
The attribute :disabled="nextButtonDisabled" is added to the button.
The nextButtonDisabled method itself looks like this:

nextButtonDisabled: function() {
    var self = this;
    var data = self.formData;
    
    if (data.param1 && data.param2)  // если поля заполнены - активируем кнопку
        return false;
    
    return true;
}
formData stores all variables.
For inputs, I prescribe v-model="formData.param1" and so on.
This works well for fields written manually, but how to specify v-model for fields that are output by v-for from such an object:
formData: [
    param1: null,
    param2: null,
    uploads: [
        {key: 1, name: 'param1', required: 1, caption: 'Параметр 1'},
        {key: 2, name: 'param2', required: 1, caption: 'Параметр 2'},
        и т.д.
    ]
]
(I probably messed up here, because I'm writing from memory... but the fields are displayed correctly, tomorrow I'll add the correct code)
Is it possible to somehow write v-model="formData.xxxxx" in v-for, where xxxxx is the name field from object, then to check these variables with the nextButtonDisabled method?
PS To write v-model so that the value is entered into the object from which the fields are formed, in my opinion, it is not an option, since in the nextButtonDisabled method they will have to be accessed by index number, which is not transparent. Ideally, it would be handled as it is given in the method code. Although, on the other hand, creating so many variables for checks is also not ideal in terms of extensibility. Can anyone suggest a better option?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-02-22
@EA-EKB

For each element in uploads, add the val property, which you use in v-model.
So nextButtonDisabled is noticeably simplified:

nextButtonDisabled() {
  return this.uploads.some(n => n.required && !n.val)
}

Separate values ​​of param1, param2, ... - throw away, instead make the computed property formData:
formData() {
  return this.uploads.reduce((acc, n) => (acc[n.name] = n.val, acc), {})
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question