📍v-for directive
- v-for 를 사용하여 배열에 기반한 엘리먼트 리스트를 렌더링할 수 있다
<ul>
<li v-for="todo in todos" :key="todo.id">
{{ todo.text }}
</li>
</ul>
- 위 예시에서 todo는 지역 변수로, source array의 원소 엘리먼트를 나타내며,
- v-for 엘리먼트 내부에서만 접근 가능 (함수 스코프처럼)
- 나열되는 엘리먼트의 key 어트리뷰트에 유니크한 값을 전달해야 함
📍리스트 렌더링을 업데이트하는 방법 2가지
1. source array에 mutating 메서드 호출
todos.value.push(newTodo)
2. array 교체
todos.value = todos.value.filter(/* ... */)
- 초간단 todo list 예시
- @submit.prevent => e.preventDefault() 기능의 submit event handler
<script setup>
import { ref } from 'vue'
// give each todo a unique id
let id = 0
const newTodo = ref('')
const todos = ref([
{ id: id++, text: 'Learn HTML' },
{ id: id++, text: 'Learn JavaScript' },
{ id: id++, text: 'Learn Vue' }
])
function addTodo() {
if (!newTodo.value) return;
const newTodoItem = { id: id++, text: newTodo.value }
todos.value = [...todos.value, newTodoItem]
newTodo.value = ''
}
function removeTodo(todo) {
todos.value = todos.value.filter((todoItem) => todo.id !== todoItem.id)
}
</script>
<template>
<form @submit.prevent="addTodo">
<input v-model="newTodo" required placeholder="new todo">
<button @click="addTodo">Add Todo</button>
</form>
<ul>
<li v-for="todo in todos" :key="todo.id">
{{ todo.text }}
<button @click="removeTodo(todo)">X</button>
</li>
</ul>
</template>