I am trying to add the value of an input as a <li>
to a <ul>
list.
I was able to add it by binding the value to the array list of lis. However, it doesn't stay there when I clean the input field. How can I fix this?
HTML code:
<div id="app">
<h1>{{ message }}</h1>
<form v-on:submit.prevent="addNewTodo">
<input type="text" v-model="todo.task">
<button type="submit">Add todo</button>
</form>
<ul>
<li v-for="todo in todos" :class="{ completed: todo.isActive }" @click="$set(todo, 'isActive', !todo.isActive)">
{{ todo.task }} <span v-on:click="deleteTodo">{{ todo.delete }}</span>
</li>
</ul>
</div>
JS Code:
var app = new Vue({
el: '#app',
data: {
message: 'List of things to do today',
todos: [
{ task: 'Have breakfast', delete:'(x)'},
{ task: 'Go to the gym', delete:'(x)'},
{ task: 'Study Vuejs', delete:'(x)'}
],
todo: {task: '', delete: '(x)'}
},
methods: {
addNewTodo: function(){
this.todos.push( this.todo );
},
deleteTodo: function(){
this.todos.shift( this.todo )
},
}
});
Here there is a sample JSfiddle: https://jsfiddle.net/mercenariomode/gwd34815/1/
You need to change the object reference, but in your case, it would be better to bind the "v-model" to the "task" property
Html code:
<form v-on:submit.prevent="addNewTodo">
<input type="text" v-model="task">
<button type="submit">Add todo</button>
</form>
JS Code:
el: '#app',
data: {
message: 'List of things to do today',
todos: [
{ task: 'Have breakfast', delete:'(x)'},
{ task: 'Go to the gym', delete:'(x)'},
{ task: 'Study Vuejs', delete:'(x)'}
],
task: '',
}
and in the addNewTodo method implement the logic of adding an object to the array
addNewTodo: function(){
let todo = {task: this.task, delete: '(x)'};
this.todos.push(todo);
this.task = ''; // clear data in input
},
JSFiddle: https://jsfiddle.net/nm29yq7d/1/