I made a basic to-do list in VueJS, but it feels really clunky and obtuse to me. One of the key things is that if the text input value is empty and the user clicks the button labeled submit then it shows a red error. When you start typing, it goes away. I tried declaring the variables in a different scope but it breaks the application. See full sample below:
// components
Vue.component('todoitem', {
template: "<li>Test Item</li>"
})
// app code
var app = new Vue({
el: '#app',
data: {
todos: [],
button: {
text: 'Hide'
},
seen: true
},
methods: {
addItem: function() {
let item = document.getElementById("list-input").value;
let error = document.getElementById("error");
if (item == "") {
error.style.display = "block";
} else {
app.todos.push({ text: item });
error.style.display = "none";
}
},
removeItem: function(index) {
this.todos.splice(index, 1);
},
removeError: function() {
let item = document.getElementById("list-input").value;
let error = document.getElementById("error");
if (item == "") {
error.style.display = "block";
} else {
error.style.display = "none";
}
},
toggleSeen: function() {
app.seen = !app.seen;
app.button.text = app.seen ? 'Hide' : 'Show';
}
}
});
#app {
width: 900px;
padding: 2em;
margin: 0 auto;
}
.todo-list {
list-style-type: square;
}
.todo-list__delete {
display: none;
}
li:hover .todo-list__delete {
display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<div id="app">
<h3>Add an Item to the list</h3>
<ul class="todo-list">
<li v-for="(todo, index) in todos">
{{ todo.text }}
<a v-on:click="removeItem(index)" class="todo-list__delete" href="#">Delete</a>
</li>
</ul>
<input v-on:keyup="removeError" type="text" id="list-input">
<input type="submit" id="list-submit" v-on:click="addItem">
<span id="error" style="color: red; display: none;">Please Enter Text</span>
<ul>
<todoitem></todoitem>
</ul>
<h2 v-if="seen">SEEN</h2>
<button id="hide-seen" v-on:click="toggleSeen">{{ button.text }}</button>
</div>
How can I make this better?