G
G
Georgy Tikhonov2020-06-18 20:49:10
Vue.js
Georgy Tikhonov, 2020-06-18 20:49:10

VueJS how to use v-model, v-for and input together?

Good afternoon, I'm currently learning Vue.JS and I've got a problem here that I can't find an answer to. There is a parent component, a form. This form has a submit button and a button to add fields.
The field itself is a child component that consists of two input elements, a checkbox and a text element. On the form, respectively, there is data, the field fieldsCount = 3. And to draw the child component, I go through it with a v-for loop. How can I make it so that the data of all three child components is stored together on the parent component? Because the button is located on the parent component.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-06-18
@Goshan41k

In the parent component, store an array of objects with data:

data: () => ({
  items: [],
}),

Based on this array, you create v-forinstances of the child component with the help of which you cling to using v-modelthe elements of the array:
<child-component v-for="(n, i) in items" v-model="items[i]"></child-component>

In the child component, you make a calculated property: wrap the data object received from the parent in a Proxy, which will intercept the setting of property values, collect a new object and send it back to the parent:
props: [ 'value' ],
computed: {
  innerValue() {
    return new Proxy(this.value, {
      set: (target, prop, val) => {
        this.$emit('input', { ...target, [prop]: val });
        return true;
      },
    });
  },
},

Use the properties of this object in v-model:
<input type="text" v-model="innerValue.someStringProp">
<input type="checkbox" v-model="innerValue.someBooleanProp">
<input type="number" v-model.number="innerValue.someNumberProp">

https://jsfiddle.net/aghpL7tf/2/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question