geckob
geckob

Reputation: 8128

Naming the model and initliaze it dynamically in Vue.js

I am aware in Vue, every reactive data properties need to be declared in the Vue instance.

I have a situation where I need pull sets of data from the server, say tickets, and I need to have a model associated to each of these data when using v-for

  1. Is there any way I can name the v-model using the ticket variable properties, ie the id. Is this possible?

    v-model="{{ ticket.id }}"

  2. If it is possible, how I declare the reactive data properties in vue instance dynamically?

Something like this:

<div id="example-1">
  <div v-for="ticket in tickets">
    <p> {{ticket.name }} </p>
    <input type="number" v-model="{{ ticket.id }}" min="0" placeholder="0">
  </div>
</div>

Upvotes: 0

Views: 168

Answers (2)

Saurabh
Saurabh

Reputation: 73649

Answer of second question

You can use vm.$set for your case. This can add new reactive properties dynamically.

Set a property on an object. If the object is reactive, ensure the property is created as a reactive property and trigger view updates.

So once you receive response from server, you can apply vm.$set on the received object.

Answer of first question

Yes, you can name the v-model using the ticket variable properties using v-model, however syntax you are using is little wrong, it should be:

v-model="ticket.id"

Upvotes: 1

Nik
Nik

Reputation: 1363

Assuming you populate the tickets array in your Vue components' data object once received from the server, you can then iterate the array of tickets as you laid out in your example.

You can then tie the input model to the ticket object property directly:

<input type="number" v-model="ticket.id" min="0" placeholder="0">

Upvotes: 0

Related Questions