Reputation: 1048
Suppose I have this kind of objects
{
[
{id:1, name:'name1'},
{id:2, name:'name2'}
]
}
Lets call the variable for this array of objects names
. I want to use the whole object itself as the v-model value
How can I use the object directly as a value of v-model inside a v-for loop? I tried something like this
I tried something like this
<div v-for="name in names">
<input v-model="name">
</div>
But its ouputting something like this [object Object]
inside an input field.
I want to dynamically change the value of this object when a user edit the specific input field with the specific object.
EDIT:
I tried using this approach https://simonkollross.de/posts/vuejs-using-v-model-with-objects-for-custom-components
But when ever I type something on the input field it only copies the original value of the input field
Upvotes: 0
Views: 11684
Reputation: 310
Just link your data array directly
new Vue({
el: '#app',
data () {
return {
names: [
{ name: 'first' },
{ name: 'second' }
]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
{{ names }}
<div v-for="(name, i) in names">
<div class="name">
<input v-model="names[i].name">
<div>
</div>
</div>
Upvotes: 2
Reputation: 123
You should be getting [Object Object] based on what you initially did. I don't think you can have an input model an array of objects.
To be clear, this is an array of objects:
let names = [
{id:1, name:'name1'},
{id:2, name:'name2'},
];
For the v-for, you should get the index just in case the id and index don't match at some point, and you should provide a key (which helpfully can just be in the index, or the id.
<div v-for="(name, i) in names" :key=name.id>
<div class="name">
<span>{{i}}</span><input v-model="name.name">
<div>
</div>
That code will create a loop that spits out each name, prefixed with an index number. This will allow your user to change the underlying data of the "names" object.
You're going to get a lot of HTML if your names object is very big, but it's necessary to do what you're looking to do. The other options you can do is forget the v-for. Only show one input, and allow your user to manually increment through your object (with a "+" & "-" button or something) until they find the right name. From there, the v-model will once again enable them to mutate the "names" object.
Upvotes: 1