You're given some existing HTML for a Todo List app. Add the following functionality to the app:
<input> field should be cleared upon successful addition.ids, data attributes, replacing some tags, etc.), but the result should remain the same visually.1<script setup>2import { ref } from 'vue';34let id = 0;56const INITIAL_TASKS = [7 { id: id++, label: 'Walk the dog' },8 { id: id++, label: 'Water the plants' },9 { id: id++, label: 'Wash the dishes' },10];1112const tasks = ref(INITIAL_TASKS);13const newTask = ref('');1415const onSummit = () => {16 tasks.value.push({ id: id++, label: newTask.value });17 newTask.value = '';18};1920const onDelete = (task) => {21 tasks.value = tasks.value.filter((t) => t.id !== task.id);22};23</script>2425<template>26 <div>27 <h1>Todo List</h1>28 <div>29 <input type="text" placeholder="Add your task" v-model="newTask" />30 <div>31 <button @click="onSummit">Submit</button>32 </div>33 </div>34 <ul>35 <li v-for="task in tasks" :key="task.id">36 <span>{{ task.label }}</span>37 <button @click="onDelete(task)">Delete</button>38 </li>39 </ul>40 </div>41</template>
We will need two reactive states: tasks and newTask.
tasks: Since there's a list of tasks that can be modified, we will need it to be part of the component's reactive state. When rendering a list of elements in Vue, we can use v-for, and it's recommended to provide a key for each item whenever possible. We cannot use task text as the key because task text is not guaranteed to be unique. For this question, we generate a unique index for each task locally using an auto-incrementing counter. The most foolproof method is to generate a unique ID for each task. Libraries like uuid come to mind.
newTask: A reactive state that binds to the new task input field. To read more, you can refer to the official documentation on form input bindings.
New tasks should be added to the end of the tasks array. We can construct a new task object with a new id and the label field, and push it to the tasks reactive state.
Having a unique id for each task object simplifies things here because we can filter the existing list and exclude the task corresponding to the id to be removed.
Using Vue, the template will automatically escape the content you try to render. So you don't need to worry about XSS yourself!
<script>, <style>, or <link>) and ensure there's no XSS.<input> is cleared after a task is added.console.log() statements will appear here.