완벽하게 Vue.js

[Vue.js][Ch1][Vue 시작하기] 조건문과 반복문

써치킴 2022. 2. 26. 06:22

디렉티브(Directive : 지시어)

HTML Element 안에 v- 접두어를 가진 attribute를 의미한다.

표현식에 직접 값을 넣거나 미리 정의해둔 뷰 인스턴스와 데이터 바인딩하여 반응적으로 표현식을 변경할 수 있다.

v-if

v-if 디렉티브 값에 true, false 값을 넣어 반응적으로 엘리먼트를 표시하거나 숨길 수 있다.

v-for

반복적으로 표현해야할 엘리먼트를 출력할 때 사용된다.

리스트 형식으로 바인딩된 데이터의 요소를 꺼내 사용할 수 있다.

 

App.vue

<template>
  <h1 @click="increase">    <!-- h1 태그를 클릭하면 increase 함수가 실행됨 -->
    {{ count }}             <!-- JavaScript에서 오는 데이터라는 의미로 {{ }} 사용 -->
  </h1>
  <div v-if="count > 4">    <!-- count가 4보다 크면 출력 -->
    4보다 큽니다!
  </div>
  <ul>
    <!-- fruits의 item을 fruit라는 변수에 할당하여 데이터로써 활용 -->
    <Fruit 
      v-for="fruit in fruits" 
      :key="fruit"
      :name="fruit">
      {{ fruit }}
    </Fruit>
  </ul>
</template>

<script>
import Fruit from '~/components/Fruit'    // 1. component 가져오기
export default {    // 객체 리터럴을 기본으로 내보내기
  components: {                           // 2. component 등록
    //Fruit: Fruit                        // 3. Fruit라는 component를 Fruit라는 이름으로 활용
    Fruit                                 // 속성과 데이터의 이름이 같으면 :뒤는 생략 가능
  },
  data() {    // data(): function() { 과 동일
    return {  // 객체 데이터를 반환
      count: 0,
      fruits : ['Apple', 'Banana', 'Cherry']
    }
  },
  methods: {
    increase() {    // 함수 생성
      // this는 script(태그) 부분을 지칭
      this.count += 1;
    }
  }

}
</script>

<style lang="scss">   // scss 문법으로 해석
 h1 {
   font-size: 50px;
   color: yellowgreen;
 }
 ul {
   li {
     font-size: 40px;
   }
 }
</style>

Fruit.vue

<template>
  <li>{{ name }}?!</li>
</template>

<script>
export default {   
  props: {
    name: {     // type이 String인 name이라는 데이터를 받는다.(데이터가 들어오지 않으면 default로 ''를 사용하겠다.)
      type: String,
      default:  ''
    }
  }

}
</script>

<style scoped lang="scss">
/* scoped : style태그는 다른 component는 영향을 미치지 않음. -> 유효범위 : 현재의 component */
  h1 {
    color:  red !important;
  }
</style>
  • style 태그에 scoped를 선언하면
    •  해당 style 태그는 다른 component는 영향을 미치지 않는다. => 유효범위 : 현재의 component

출력