Blog>
Snippets

Reactive Todo List with Computed Properties

Build a todo list application that reacts to additions and deletions, using computed properties to filter completed tasks.
<div id="app">
  <h1>Reactive Todo List</h1>
  <input type="text" v-model="newTodo" @keyup.enter="addTodo">
  <button @click="addTodo">Add</button>
  <ul>
    <li v-for="(todo, index) in filteredTodos" :key="index">
      <input type="checkbox" v-model="todo.completed">
      <span :class="{'completed': todo.completed}">{{ todo.text }}</span>
      <button @click="removeTodo(index)">Delete</button>
    </li>
  </ul>
  <p>
    <label><input type="checkbox" v-model="showCompleted"> Show Completed Tasks</label>
  </p>
</div>
HTML structure with Vue.js directives to create a reactive Todo List with the ability to add, display, complete, and remove tasks. Includes a computed property to filter out completed tasks based on user preference.
new Vue({
  el: '#app',
  data: {
    newTodo: '',
    todos: [],
    showCompleted: true
  },
  computed: {
    filteredTodos: function() {
      return this.showCompleted ? this.todos : this.todos.filter(todo => !todo.completed);
    }
  },
  methods: {
    addTodo: function() {
      if(this.newTodo.trim()) {
        this.todos.push({ text: this.newTodo, completed: false });
        this.newTodo = '';
      }
    },
    removeTodo: function(index) {
      this.todos.splice(index, 1);
    }
  }
});
Vue.js instance that binds the data and methods to the HTML structure for reactivity. Includes a computed property to filter todos, and methods to add and remove todos.
#app {
  font-family: Arial, sans-serif;
}

.completed {
  text-decoration: line-through;
  color: grey;
}
CSS styles define the font and completed task text styling.