Reputation: 23256
How do I bind the properties of a form that is generated dynamically?
<div class="form-group" v-for="col in colInfo">
<template v-if="col.Type == 'text'">
<label class="badge badge-info">{{col.Field}}</label>
<textarea class="form-control form-control-md" rows="3" v-on:change="updateInsertMap(col.Field)"></textarea>
</template>
<template v-else>
<label class="badge badge-info">{{col.Field}}</label>
<input type="text" class="form-control form-control-md" v:on:change="updateInsertMap(col.Field)">
</template>
</div>
When the submit button is clicked, I need to get all the values before sending it to the server. How could I keep track of the values?
Upvotes: 1
Views: 45
Reputation: 4438
Use v-model
instead.
const app = new Vue({
el: '#app',
data: {
colInfo: [
{Type: 'input', Field: 'First Name', Value: 'John' },
{Type: 'input', Field: 'Last Name', Value: 'Doe' },
{Type: 'text', Field: 'Comment', Value: '3141592653589793238462643383279502' }
],
dataToBeSent: undefined
},
methods: {
submit() {
this.dataToBeSent = this.colInfo.map((col) => col.Value)
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<div id="app">
<div class="form-group" v-for="col in colInfo">
<template v-if="col.Type == 'text'">
<label class="badge badge-info">{{col.Field}}</label>
<textarea
class="form-control form-control-md"
rows="3"
v-model="col.Value">
</textarea>
</template>
<template v-else>
<label class="badge badge-info">{{col.Field}}</label>
<input
type="text"
class="form-control form-control-md"
v-model="col.Value">
</template>
</div>
<button v-on:click="submit()">Submit</button>
<div>
<h3>colInfo</h3>
<div>{{colInfo}}</div>
</div>
<div>
<h3>Submitted Item</h3>
<div>{{dataToBeSent}}</div>
</div>
</div>
Upvotes: 0
Reputation: 23256
I figured this out! There is actually a clever way to achieve this.
We need to define a data property that will be an empty object
. So the point is to bind this object to the form. The key in the object could be id
, name
or any key that helps the purpose of identification and the value will automatically become the value of the field.
Here is the example:
<template v-if="table.length > 0 && colInfo.length > 0">
<div class="form-group" v-for="col in colInfo">
<template v-if="col.Type == 'text'">
<label class="badge badge-info">{{col.Field}}</label>
<textarea class="form-control form-control-md" rows="3" v-model="insertMap[col.Field]"></textarea>
</template>
<template v-else>
<label class="badge badge-info">{{col.Field}}</label>
<input type="text" class="form-control form-control-md" v-model="insertMap[col.Field]">
</template>
</div>
</template>
In the above example, insertMap
is the object that is a binding property for this form. Hope this helps.
Upvotes: 1