개발 도구 (Development Tools)/Vue

Vue - 조건부 클래스

BiCute 2023. 2. 13. 08:00
반응형

 

Vue.js에서 조건에 따라 클래스를 지정하려면 v-bind디렉티브를 사용하여 부울 값(참, 거짓)으로 평가되는 표현식에 클래스를 바인딩할 수 있습니다.

 

 

단일 조건부 클래스

  :class="{'클래스명': '조건'}"

다음은 단일 조건부 클래스의 예입니다.

<template>
  <div v-bind:class="{ active: isActive }"></div>
</template>

<script>
export default {
  data() {
    return {
      isActive: true
    }
  }
}
</script>

isActive의 속성이 true인 경우 div 요소에 active 클래스가 적용 됩니다.

 

 

 

다중 조건부 클래스

:class="{'클래스명': '조건', '클래스명': '조건'}"

다음은 다중 조건부 클래스의 예입니다.

<template>
  <div v-bind:class="{ active: isActive, 'text-danger': hasError }"></div>
</template>

<script>
export default {
  data() {
    return {
      isActive: true,
      hasError: false
    }
  }
}
</script>

isActive가 ture인 경우 active 클래스를 추가하고,

hasError가 true인 경우 'text-danger' 클래스를 추가합니다.

 

 

 

삼항 연산자를 사용한 조건부 클래스

:class="[조건 ? '조건이 true일 경우의 클래스' : '조건이 false일 경우의 클래스']"

다음은 삼항 연산자를 사용한 조건부 클래스의 예입니다.

<template>
  <div v-bind:class="isActive ? 'active' : 'inactive'"></div>
</template>

<script>
export default {
  data() {
    return {
      isActive: true
    }
  }
}
</script>

isActive의 값이 ture면 'active' 클래스를 추가 되고, 그렇지 않다면 inactive 클래스가 추가됩니다.

 

 

 

Computed를 사용한 조건부 클래스

조건이 많아 인라인 양식으로 사용하기 어려울 경우, computed를 사용하여 응용할 수 있습니다.

<template>
  <div v-bind:class="classObject"></div>
</template>

<script>
export default {
  computed: {
    classObject() {
      return {
        active: this.isActive,
        'text-danger': this.hasError,
        'text-success': this.isSuccess
      }
    }
  },
  data() {
    return {
      isActive: true,
      hasError: false,
      isSuccess: true
    }
  }
}
</script>

각각의 data 속성에 따라 'active', 'text-danger' 및 'text-success' 클래스가 추가됩니다.

 

 

참고: 유효한 식별자의 조건

• 문자, 밑줄(_) 또는 달러 기호($)로 시작해야 합니다.
• 문자, 숫자, 밑줄 및 달러 기호를 포함할 수 있습니다.
• 예약어(예: "let", "if", "class" 등)일 수 없습니다.

 

위의 규칙을 따르고 공백을 포함하지 않는 문자열은 v-bind:class 지시문에서 클래스 이름으로 사용될 때 따옴표 없이 작성할 수 있습니다.

따옴표 없이 작성할 수 있는 유효한 식별자를 예를들면 다음과 같습니다.

active, isActive, _private, $special, myVariableName

 

JavaScript는 대소문자를 구분하므로 active와 Active는 서로 다른 식별자로 간주됩니다.

반응형