Brendan B.
Brendan B.

Reputation: 31

VueJS nested data model

I am relatively new to VueJS and am wondering how to nest/reference component's properties within others, so that the v-model binding will actually update them properly.

To illustrate, I am trying to do something like this.

Template:

<table>
    <tr v-for="field in myFields">
        <td class="label">{{field.label}}</td>
        <td class="user-control">
            <input v-model="field.model">
        </td>
    </tr>
</table>

Component:

export default {
    data () {
        return {
            myFields: [
                {
                    "label": "label",
                    "model": this.propertyOne
                },
                {
                    "label": "label",
                    "model": this.propertyTwo
                }
            ],
            propertyOne: "",
            propertyTwo: ""
        }
    }
}

In this example, I am expecting the template to render the propertyOne and propertyTwo values (e.g. empty string) in the inputs at first, and then have those values be updated when I change them via the input, like it would normally do with the v-model.

The first works, which means that if I set to propertyOne to "Foo", it gets used as the input value initially, but subsequent changes still don't update the properties. I would love for this to work so that I can leverage the power of the v-for hook instead of having to write down a massive static template if I have more than 10 fields.

Upvotes: 1

Views: 3448

Answers (1)

Saurabh
Saurabh

Reputation: 73619

When you do: "model": this.propertyTwo this does not make sure that all subsequent changes to propertyTwo will be reflected in the model. To Achieve this there are few options available for you.

You can use watcher, so whenever propertyTwo will change you can execute a piece of code, like following:

watch: {
  // whenever propertyTwo changes, this function will run
  propertyTwo: function (newProp) {
    this.myFields[1].model = newProp
  }
},

You can also use Computed-Properties or method, which will be reactive if any associated data changes, they will execute.

Upvotes: 1

Related Questions