Created
April 10, 2024 20:06
-
-
Save helabenkhalfallah/09c4b003323e98efb16217c1dd429635 to your computer and use it in GitHub Desktop.
TodoList
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
import { onMount } from 'svelte'; | |
// Define an array of tasks | |
let tasks = [ | |
{ id: 1, title: 'Complete homework', completed: false }, | |
{ id: 2, title: 'Do laundry', completed: false }, | |
{ id: 3, title: 'Buy groceries', completed: false } | |
]; | |
// Function to mark a task as completed | |
const toggleTaskCompletion = (taskId) => { | |
tasks = tasks.map(task => { | |
if (task.id === taskId) { | |
return { ...task, completed: !task.completed }; | |
} | |
return task; | |
}); | |
}; | |
// Reactive statement to count completed tasks | |
$: completedTasksCount = tasks.filter(task => task.completed).length; | |
// Reactive statement to update UI when tasks change | |
$: { | |
console.log('Tasks updated:', tasks); | |
} | |
</script> | |
{#if tasks.length > 0} | |
<!-- Render a list of tasks if there are tasks available --> | |
<ul> | |
{#each tasks as task (task.id)} | |
<!-- Click event handler toggles task completion --> | |
<li | |
on:click={() => toggleTaskCompletion(task.id)} | |
class:completed={task.completed} | |
> | |
{task.title} | |
</li> | |
{/each} | |
</ul> | |
{:else} | |
<!-- Display a message if no tasks are available --> | |
<p>No tasks available.</p> | |
{/if} | |
<!-- Display the total number of completed tasks --> | |
<p>Total completed tasks: {completedTasksCount}</p> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment