S
S
Scott2019-06-03 12:08:24
Vue.js
Scott, 2019-06-03 12:08:24

How to initialize a large number of properties of the same type?

There is a form, it has about 20 inputs.
How can I add them to data, without prescribing 20 times in a row input1: '', input2: ''?
those

new Vue({
  el: '#form',
  data: {
    // как это сократить?
    input1: '',
    input20: ''
  },
  beforeMount() { // какой тут хук использовать?
    const fields = ['input1', 'input2']

    fields.forEach(item => this[item] = '') // я правильно добавляю в this, а не в this.$data?
  }
})

And, of course, so that these saints work with v-modeland can be accessed in the template as{{input1}} {{input2}}...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2019-06-03
@g-unit

Make an array:

data: () => ({
  input: Array(20).fill(''),
  ...
}),

D
Denis Gribanov, 2019-06-03
@gribanov2la

I disagree a bit with the concept.
If I were you, I would do all 20 properties, but at the same time I would use semantic naming. (well, not input1, but email). In this case, you lose "savings on matches", but your code becomes more meaningful and readable.
Regarding the "cleaning" of values, you can either make a function to clear all fields, or make something like defaultState for the entire list of fields, and simply overwrite working properties with it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question