SimpleTodo-Vuejs

by Foci Wang

HTML

<script src="https://cdn.jsdelivr.net/vue/latest/vue.js"></script>
<div id="todos">
  <h4>Todos</h4>
  <input v-model="newTodo" @keyup.enter="addTodo" placeholder="new to do" />
  <ul>
    <li v-for="todo in todoList">
      <span>
        <input type="checkbox" @click="toggleState(todo)" checked="{{ todo.done }}"/> 
        <span class="{{ todo.done ? 'done-todo' : 'active-todo'}}">
          {{ todo.content }}
        </span>
      <button @click="removeTodo(todo)">X</button>
      </span>
    </li>
  </ul>
  <div v-if="todos.length > 0">
    <span class="left-todo-view">{{ activeTodos.length }} {{ activeTodos.length > 1 ? 'items' : 'item' }} Left </span>
    <input type="radio" name="typeRadioButton" v-model="showType" value="all" clicked/>All
    <input type="radio" name="typeRadioButton" v-model="showType" value="active" />Active
    <input type="radio" name="typeRadioButton" v-model="showType" value="done" />Done
    <button v-if="doneTodos.length > 0" class="clear-all-done" @click="clearAllDoneTodos">Clear all done</button>
  </div>
</div>

CSS

ul {
  padding: 5px;
}

li {
  list-style-type: none;
}

.active-todo {
  color: black;
  text-decoration: none;
}

.done-todo {
  color: #aaa;
  text-decoration: line-through;
}

.left-todo-view {
  background-color: #eee;
  padding: 3px;
  border-radius: 3px;
  color: green;
  margin-right: 10px;
}

.clear-all-done {
  background-color: #eee;
  padding: 3px;
  border-radius: 3px;
  color: red;
  margin-left: 10px;
}

JavaScript

Array.prototype.remove = function(item) {
   this.splice(this.indexOf(item), 1)
 };

 Array.prototype.select = function(selection) {
   var selected = []
   var _this = this
   this.forEach(function(item) {
     if (selection(_this.indexOf(item), item)) {
       selected.push(item)
     }
   })
   return selected
 };

 new Vue({
   el: "#todos",
   data: {
     newTodo: '',
     todos: [],
     showType: 'all'
   },
   computed: {
     todoList: function() {
       switch (this.showType) {
         case 'all':
           return this.todos
         case 'active':
           return this.activeTodos
         case 'done':
           return this.doneTodos
       }
     },
     activeTodos: function() {
       return this.todos.select(function(_, todo) {
         return !todo.done
       })
     },
     doneTodos: function() {
       return this.todos.select(function(_, todo) {
         return todo.done
       })
     }
   },
   methods: {
     addTodo: function() {
       if (this.newTodo != '') {
         var newTodo = {
           done: false,
           content: this.newTodo
         }
         this.todos.push(newTodo)
         this.newTodo = ''
       }
     },
     toggleState: function(todo) {
       todo.done = todo.done ? false : true
     },
     clearAllDoneTodos: function() {
       this.todos = this.activeTodos
     },
     removeTodo: function(todo) {
       this.todos.remove(todo)
     }
   }
 })