I have an input text field with a v-model attached, and every time someone hits the "Add" button, another input text get added to the DOM with the same v-model attached. I thought I'd then get an array of the v-model values, but it only gets the value of the first v-model input:
<div id="app">
<div id="references">
<input v-model="references" type="text">
</div>
<button @click="addReference">Add</button>
</div>
The html I append to the dom is triggered by the addReference method:
addReference: function(e) {
e.preventDefault();
console.log(this.references);
var inputEl = '<input v-model="references" type="text">';
$('#references').append(inputEl);
}
Is this something Vuejs can't do? Is there a different approach of gathering values from dynamic dom elements with Vuejs?
new Vue({
el: "#app",
data: {
references: "text"
},
methods: {
addReference: function(e) {
e.preventDefault();
console.log(this.references);
var inputEl = '<input v-model="references" type="text">';
$('#references').append(inputEl);
}
}
})
input {
display: block;
margin: 1px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="app">
<div id="references">
<input v-model="references" type="text">
</div>
<button @click="addReference">Add</button>
</div>
Here's a demo of the above:https://jsfiddle.net/sajadweb/mjnyLm0q/11
If you were asking how to do it in vue2 and make options to insert and delete it, please, have a look an js fiddle
You're thinking too DOM, it's a hard as hell habit to break. Vue recommends you approach it data first.
It's kind of hard to tell in your exact situation but I'd probably use a
v-for
and make an array offinds
to push to as I need more.Here's how I'd set up my instance:
And here's how I'd set up my template:
Although, I'd try to use something besides an
index
for thekey
.Here's a demo of the above: https://jsfiddle.net/crswll/24txy506/9/