finox
finox

Reputation: 21

Bind v-model dynamically in v-for loop using string as a model name

I am trying to render several components using <component v-bind:is="..."> in a v-for loop. That works well, now I need to assign v-model in the loop.

This is what I have - an array of objects, each object represents component, with it's props, and the model

let formA = [{
        component: 'formPartA',
        props: {
            value1: true,
            value2: "Hello",
        },
        model: "formData.formA" // This is what I need to use in the loop

    },
    {
        component: 'formPartB',
        props: {
            value1: true,
        },
        model: "formData.formB"

    },
];

The data:

data() {
    return {
        form: formA,
        formData: {
            formA: null,
            formB: null,
        },
    }
}

So far I was able to render it succesfully:

<template v-for="(c, index) in form">
    <component
        v-bind:is="c.component"
        v-bind="c.props"
    ></component>
</template>

The components are working with the props defined in the array. All I want now is to add the v-model, however I can't get this to work.

I tried to bind it:

v-model="c.model"
:v-model="c.model"

or alter the c.model

model: "formData.formA"
model: formData.formA
model: this.formData.formA

and nothing works for me.

I even tried a workaround to just rewrite v-model to v-bind:value with v-on:input, this didn't work either.

I will be grateful for any help!

Upvotes: 1

Views: 82

Answers (1)

finox
finox

Reputation: 21

Well it looks like I just found a solution to my problem:

v-model="formData[c.model]"

In the let formA = ...

model: "formA"
data() {
    return {
        form: formA,
        formData: {
            formA: null,
            formB: null,
        }, 
    }
}

Upvotes: 1

Related Questions