검색 input 에 v-model="searchText" 처럼 v-model 양방향 데이터 처리를 해주고
다음과 같이 필터 함수 또는 computed 추가
const searchText = ref(""); const filteredTodos = computed(() => { if (searchText.value) { return todos.value.filter((todo) => { return todo.subject.includes(searchText.value); }); } return todos.value; });
v-for="(todo, index) in filteredTodos"
v-for 목록 처리는 필터 처리된 filteredTodos 를 넣어주면 된다.
<template> <div class="container"> <h2>To-Do List</h2> <input type="text" class="form-control mt-5 mb-5" v-model="searchText" placeholder="Search" /> <form class="d-flex" @submit.prevent="onSubmit"> <div class="flex-grow-1 mr-2"> <input type="text" class="form-control" v-model="todo" placeholder="Type new to-do" /> </div> <div> <button class="btn btn-primary">Add</button> </div> </form> <div v-if="!filteredTodos.length">검색 결과가 없습니다.</div> <div class="card mt-3" v-for="(todo, index) in filteredTodos" :key="todo.id" > <div class="card-body p-2 d-flex align-items-center"> <div class="form-check flex-grow-1"> <input type="checkbox" class="form-check-input" v-model="todo.completed" @change="toggleTodo(index)" /> <label class="form-check-label" :class="{ todo: todo.completed ? 'todo' : '' }" > {{ todo.subject }} </label> </div> <div> <button class="btn btn-danger btn-sm">Delete</button> </div> </div> </div> </div> </template> <script> import { ref, computed } from "vue"; export default { setup() { const todos = ref([ { id: 1, subject: "강아지" }, { id: 2, subject: "송아지" }, { id: 3, subject: "고양이" }, ]); const searchText = ref(""); const filteredTodos = computed(() => { if (searchText.value) { return todos.value.filter((todo) => { return todo.subject.includes(searchText.value); }); } return todos.value; }); return { todos, searchText, filteredTodos, }; }, }; </script> <style scoped> .blue { color: blue; } </style>
댓글 ( 4)
댓글 남기기