1π
β
Just update current index, so v-model
update recently added teacher
.
v-model="teachers[index].firstName"
new Vue({
el: '#app',
data() {
return {
index: 0,
teachers: [
{
firstName: '',
lastName: '',
},
],
students: [],
}
},
methods: {
pushTeacher() {
this.index++
this.teachers.push({
firstName: '',
lastName: '',
})
},
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div>
<div>
<input type="text" placeholder="Teachers' first name" v-model="teachers[index].firstName" />
<input type="text" placeholder="Teachers' last name" v-model="teachers[index].lastName" />
<input type="button" value="Push Teacher" @click="pushTeacher" />
</div>
<ul>
<li v-for="(teacher, index) in teachers" :key="index">{{ teacher.firstName}} {{ teacher.lastName }}</li>
</ul>
</div>
</div>
π€Andrew Vasylchuk
2π
You can use v-for instead.
For example
new Vue({
el: "#app",
data: {
todos: [{
id: 1,
text: "Learn JavaScript",
done: false,
model: 'javascript'
},
{
id: 2,
text: "Learn Vue",
model: 'reactjs',
done: false
},
{
id: 3,
text: "Play around in JSFiddle",
done: true,
model: 'vue'
},
]
},
methods: {
toggle: function(todo) {
todo.done = !todo.done
},
showValues() {
console.log(this.todos);
},
addField() {
this.todos.push({
model: 'test'
});
this.$forceUpdate();
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button @click="addField">
Add Field
</button>
<ul>
<li v-for="(todo, index) in todos">
<input v-model="todo.model">
</li>
</ul>
<button @click="showValues">
Show Values
</button>
</div>
π€jayrcodes
Source:stackexchange.com