Vue.js의 렌더링과 가정문

송민경's avatar
Sep 09, 2024
Vue.js의 렌더링과 가정문

1. 렌더링

  • 특정 조건에 따라 요소를 화면에 나타내거나 숨기는 작업
  • 조건부 렌더링을 통해 특정 조건이 만족될 때만 HTML 요소를 DOM에 추가하거나 제거 가능
 

2. v-if

  • 조건이 참일 때만 요소를 렌더링
  • 조건이 거짓일 때는 요소가 DOM에서 제거
  • 새롭게 생성할 경우 사용
  • 같은 레벨(한 부모안에 형제)로 이어져있어야 함
    • 조건문 안에 다른 태그가 들어가면 에러 발생
<template> <h2>당신의 나이는 {{ age }}입니다</h2> <p v-if="age > 18">당신은 어른입니다</p> <p v-else-if="age >50">당신은 어르신입니다</p> <p v-else>당신은 아이입니다</p> <!--같은 레벨이어야 함--> </template>
notion image
notion image
notion image
notion image

3. v-show

  • 조건에 따라 요소의 display CSS 속성을 변경
  • 요소는 항상 DOM에 존재하지만, 조건이 거짓일 때는 숨겨짐
  • true일 경우
    • <!--HTML 코드 작성--> <template> <h2 v-if="display">true -> 보입니다</h2> <h2 v-show="display">true -> 보입니다</h2> </template>
      notion image
  • false일 경우
    • show는 태그만 생성이 됨
    • 컴포넌트라고 많은 기능이 담긴 코드를 가져올 경우가 있음
    • if와 달리 한번 생성해놓고 display만 닫았다가 열 수 있음
    • 렌더링 하는데 시간이 많이 걸릴 경우 이용하면 좋음
    • <!--HTML 코드 작성--> <template> <h2 v-if="display">v-if 보입니다</h2> <h2 v-show="display">v-show 보입니다</h2> </template> <!--Java Script 코드 작성--> <script> export default { name: 'App', // 컴포넌트의 이름 components: {}, data() { return { age: 10, display: false }; } } </script>
      notion image
 

4. 반복문

  • 데이터를 기반으로 리스트나 배열의 요소를 반복해서 렌더링하는 데 사용
  • v-for
    • 배열이나 객체의 각 항목을 반복하여 DOM 요소를 렌더링
    • 반복할 데이터와 각 항목에 대한 키를 지정해야 함
  • 키 속성 (:key)
    • v-for를 사용하여 반복적으로 생성되는 요소의 고유성을 식별하기 위해 사용
    • 각 반복 항목에 대해 고유한 값을 가짐
    • 이 키를 사용하여 어떤 항목이 변경되었는지, 추가되었는지, 삭제되었는지를 추적
    • 장점
      • 성능 최적화
        • key를 사용하여 가상 DOM과 실제 DOM 간의 차이를 더 효율적으로 계산할 수 있음
        • 불필요한 DOM 업데이트를 방지하고, 렌더링 성능을 향상
      • 안정성
        • 동일한 컴포넌트가 동일한 데이터를 가지더라도, key를 통해 Vue는 각 항목의 위치와 상태를 정확히 추적할 수 있음
        • 데이터 변경 시에 예상치 못한 UI 문제를 방지
      notion image
<!--HTML 코드 작성--> <template> <h2>{{ animals }}</h2> </template> <!--Java Script 코드 작성--> <script> export default { name: 'App', // 컴포넌트의 이름 components: {}, data() { return { age: 10, display: false, animals: ['cat', 'dog', 'rabbit', 'bird'] }; } } </script>
notion image
  • key값 사용
    • <template> <h2 v-for="animal in animals" :key="animal">{{ animal }}</h2> </template>
      notion image
  • 배열의 요소가 중복될 수 있기 때문에 배열의 인덱스를 파라미터로 받아 키로 사용
    • <template> <h2 v-for="(animal, index) in animals" :key="animal">{{ animal }} 인덱스는 {{ index }}</h2> </template>
      notion image
  • 오브젝트들의 배열과 인덱스를 파라미터로 받아 키로 사용
    • <!--HTML 코드 작성--> <template> <h2 v-for="(animal, index) in animals" :key="animal">{{ animal }} 인덱스는 {{ index }}</h2> <ul> <li v-for="(user, index) in users" :key="index">{{ user.name }}</li> </ul> </template> <!--Java Script 코드 작성--> <script> export default { name: 'App', // 컴포넌트의 이름 components: {}, data() { return { age: 10, display: false, animals: ['cat', 'dog', 'rabbit', 'bird'], users: [ {name: 'min', age: 32, gender:'woman'}, {name: 'sue', age: 30, gender:'man'} ] }; } } </script>
      notion image
      <template> <h2 v-for="(animal, index) in animals" :key="animal">{{ animal }} 인덱스는 {{ index }}</h2> <ul> <li v-for="(user, index) in users" :key="index">이름은 {{ user.name }}, 나이는 {{ user.age }}, 성별은 {{ user.gender }}</li> </ul> </template>
      notion image
  • 오브젝트 안에 배열 요소 사용
    • <!--HTML 코드 작성--> <template> <h2 v-for="(animal, index) in animals" :key="animal">{{ animal }} 인덱스는 {{ index }}</h2> <ul> <li v-for="(user, index) in users" :key="index">이름은 {{ user.name }}, 나이는 {{ user.age }}, 성별은 {{ user.gender }} <p v-for="hobby in user.hobbies" :key="hobby">{{ hobby }}</p> </li> </ul> </template> <!--Java Script 코드 작성--> <script> export default { name: 'App', // 컴포넌트의 이름 components: {}, data() { return { age: 10, display: false, animals: ['cat', 'dog', 'rabbit', 'bird'], users: [ {name: 'min', age: 32, gender:'woman', hobbies:["sports", "k-pop"]}, {name: 'sue', age: 30, gender:'man', hobbies:["eating", "swimming"]} ] }; } } </script>
      notion image
  • v-if와 v-for는 함께 사용할 수 없음
    • <template> <h2 v-if="animal !='cat'" v-for="(animal, index) in animals" :key="animal">{{ animal }} 인덱스는 {{ index }}</h2> <ul> <li v-for="(user, index) in users" :key="index">이름은 {{ user.name }}, 나이는 {{ user.age }}, 성별은 {{ user.gender }} <p v-for="hobby in user.hobbies" :key="hobby">{{ hobby }}</p> </li> </ul> </template>
      notion image
 
  • v-for 안에 태그를 추가하여 v-if 사용하기
    • <template> <h2 v-for="(animal, index) in animals" :key="animal"> <span v-if="animal != 'cat'">{{ animal }} 인덱스는 {{ index }}</span></h2> <ul> <li v-for="(user, index) in users" :key="index">이름은 {{ user.name }}, 나이는 {{ user.age }}, 성별은 {{ user.gender }} <p v-for="hobby in user.hobbies" :key="hobby">{{ hobby }}</p> </li> </ul> </template>
      notion image
  • 템플릿 안에 템플릿 사용
    • <template> 태그를 사용하면 반복 요소(v-for)와 조건부 렌더링(v-if)을 함께 사용할 수 있음
    • <template>은 DOM에서 제거되므로 실제로 렌더링되지 않음
    • 복잡한 구조를 깔끔하게 유지 가능
      • HTML 구조에서 중첩된 태그를 생성하지 않고도 복잡한 구조 구성
      • 추가적인 불필요한 태그가 생성되지 않아서 HTML이 더 깔끔해짐
      <template> <template v-for="(animal, index) in animals" :key="animal"> <h2 v-if="animal != 'cat'">{{ animal }} 인덱스는 {{ index }}</h2> </template> </template>
      notion image
Share article
RSSPowered by inblog