[Vue.js] tutorial - 7. List Rendering

2024. 7. 31.·🎨 프론트엔드 공부/Vue & Nuxt

📍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>
'🎨 프론트엔드 공부/Vue & Nuxt' 카테고리의 다른 글
  • [Vue.js] tutorial - 9. Lifecycle and Template Refs
  • [Vue.js] tutorial - 8. Computed Property
  • [Vue.js] tutorial - 6. Conditional Rendering
  • [Vue.js] tutorial - 5. Form Bindings
지식물원
지식물원
지식이 자라는 식물원!
  • 지식물원
    지식물원
    지식물원
  • 전체
    오늘
    어제
    • 분류 전체보기 (519) N
      • 🎨 프론트엔드 공부 (244) N
        • JS & TS (92)
        • HTML & CSS (22)
        • React & Next (51) N
        • Vue & Nuxt (22)
        • 기타 (57)
      • 🤓 기술 학습 & 공부 기록 (116)
        • Node.js (0)
        • Python (37)
        • 백엔드 (0)
        • 딥러닝 (1)
        • 컴퓨터 일반 (72)
        • 개발 인프라 (6)
      • 👨‍💻 프로젝트 경험 (16)
        • Work (0)
        • Toy (16)
      • ⚙️ 개발 팁 & 노하우 (23)
        • 프론트엔드 (6)
        • 기타 (17)
      • ☕️ 커리어 & 인터뷰 준비 (88)
        • 코딩 테스트 (88)
      • 📰 기술 트렌드 & 생각 정리 (4)
      • 📚 기타 (25)
        • 마케팅 (15)
        • 비개발서적 (10)
  • 블로그 메뉴

    • 태그
  • 링크

  • 공지사항

    • 모바일 접속 시 코드 하이라이팅 깨질 때
  • 인기 글

  • hELLO· Designed By정상우.v4.10.3
지식물원
[Vue.js] tutorial - 7. List Rendering
상단으로

티스토리툴바