Hi I have a form like this:
<tr v-for="(post, index) in posts" v-bind:index="index">
<td>{{ post.rut }}</td>
<td>{{ post.names }} {{ post.father_lastname }} {{ post.mother_lastname }}</td>
<td>
<input type="number" class="form-control" id="exampleInputEmail1" v-model="form.amount[index]" placeholder="Ingresa el monto">
</td>
</tr>
How you can see it has v-model="form.amount[index]" but what I want to do it's this:
<input type="number" class="form-control" id="exampleInputEmail1" v-model="form.amount[post.rut]" placeholder="Ingresa el monto">
I mean I ant to assign my own index my custom index I wonder how can I do that??
My vuejs code is this:
data: function() {
return {
form: {
amount: [],
},
I declared amount array in vuejs how you can see above but I need to assign my own index in array because if I send the data and I check the array in this moment, it is:
0 => value, 1 => value
but I need to do this
'2714155' => value, '4578745' => value...
how can I do that? Thanks
CodePudding user response:
Declare your data as an object, then assign value to specific keys.
data() {
return {
form: {
amount: {},
},
}
}
You can use your desired layout as is.
<input
type="number"
class="form-control"
id="exampleInputEmail1"
v-model="form.amount[post.rut]" <-- here you assign a specific key
placeholder="Ingresa el monto">
CodePudding user response:
You can achieve this by using an object instead of an array, as javascript
doesn't have associative array's like php
. You can achieve an associative array with the help of objects instead.
See the working example below:
Vue.config.productionTip = false
Vue.config.devtools = false
new Vue({
el: '#app',
data: {
posts: [{
rut: 2714155,
names: 'John',
father_lastname: 'Doe',
mother_lastname: 'Foo'
},
{
rut: 4578745,
names: 'Lion',
father_lastname: 'Doe',
mother_lastname: 'Bar'
}
],
form: {
amount: {
'2714155': 1,
'4578745': 2
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<table>
<tr v-for="post in posts" :key="post.rut">
<td>{{ post.rut }}</td>
<td>{{ post.names }} {{ post.father_lastname }} {{ post.mother_lastname }}</td>
<td>
<input type="number" class="form-control" id="exampleInputEmail1" v-model="form.amount[post.rut]" placeholder="Ingresa el monto">
<span>Model Value: {{ form.amount[post.rut] }}</span>
</td>
</tr>
</table>
</div>