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:
Add
The html I append to the dom is triggered by the addReference method:
addReference: function(e) {
e.preventDefault();
console.log(this.references);
var inputEl = '';
$('#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 = '';
$('#references').append(inputEl);
}
}
})
input {
display: block;
margin: 1px;
}
Add
解决方案
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 of finds to push to as I need more.
Here's how I'd set up my instance:
new Vue({
el: '#app',
data: {
finds: []
},
methods: {
addFind: function () {
this.finds.push({ value: '' });
}
}
});
And here's how I'd set up my template:
Finds
New Find
Although, I'd try to use something besides an index for the key.