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 tho
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:
<div id="app">
<h1>Finds</h1>
<div v-for="(find, index) in finds">
<input v-model="find.value" :key="index">
</div>
<button @click="addFind">
New Find
</button>
</div>
Although, I'd try to use something besides an index
for the key
.
Here's a demo of the above: https://jsfiddle.net/crswll/24txy506/9/
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
new Vue({
el: '#app',
data: {
finds: []
},
methods: {
addFind: function () {
this.finds.push({ value: 'def' });
},
deleteFind: function (index) {
console.log(index);
console.log(this.finds);
this.finds.splice(index, 1);
}
}
});
<script src="https://unpkg.com/vue@2.5.3/dist/vue.js"></script>
<div id="app">
<h1>Finds</h1>
<div v-for="(find, index) in finds">
<input v-model="find.value">
<button @click="deleteFind(index)">
delete
</button>
</div>
<button @click="addFind">
New Find
</button>
<pre>{{ $data }}</pre>
</div>
Here's a demo of the above:https://jsfiddle.net/sajadweb/mjnyLm0q/11
new Vue({
el: '#app',
data: {
users: [{ name: 'sajadweb',email:'sajadweb@outlook.com' }]
},
methods: {
addUser: function () {
this.users.push({ name: '',email:'' });
},
deleteUser: function (index) {
console.log(index);
console.log(this.finds);
this.users.splice(index, 1);
if(index===0)
this.addUser()
}
}
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<h1>Add user</h1>
<div v-for="(user, index) in users">
<input v-model="user.name">
<input v-model="user.email">
<button @click="deleteUser(index)">
delete
</button>
</div>
<button @click="addUser">
New User
</button>
<pre>{{ $data }}</pre>
</div>