Client/vue

클래스와 스타일 바인딩

이건욱 2020. 9. 14. 18:06

v-bind

Vue.js에서 v-bind을 통해서 데이터 바인딩을 할수가 있습니다.

 

하지만 표현식을 계속 사용하다보면 가독성도 떨어지고 오류가 발생할수 있기 때문에 이러한 이유로 객체 또는 배열을 제공을 합니다.

 

HTML 클래스 바인딩

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

위와 같이 class안에 객체로 전달을 하였습니다.

이렇게 전달을 했을때 데이터안의 isActivity 참속성에 의해서 존재 여부를 결정짓게 됩니다.

data: {
  isActive: true
}

 

또는 위와같이 인라인 객체를 할필요는 없습니다. 아래와 같이 객체를 넣어도 동일한 작업을 합니다.

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

data: {
  classObject: {
    active: true,
    'text-danger': false
  }
}

보통은 data안에 다가 정의하지만 경우에 따라서 computed속성에 작업을 할수가 있습니다.

data: {
  isActive: true,
  error: null
},
computed: {
  classObject: function () {
    return {
      active: this.isActive && !this.error,
      'text-danger': this.error && this.error.type === 'fatal'
    }
  }
}

배열

위에서는 객체를 통해 정의를 했지만 이번에는 배열을 통해서 지정 할수가 있습니다.

<div v-bind:class="[activeClass, errorClass]"></div>
##<div v-bind:class="[isActive ? activeClass : '', errorClass]"></div>##

data: {
  activeClass: 'active',
  errorClass: 'text-danger'
}

 

Style 바인딩

아래와 같이 style 객체는 css처럼 보이지만 javascript 객체이기 때문에 속성에 camelCase와 kebab-case를 사용할수 있습니다.

<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>

data: {
  activeColor: 'red',
  fontSize: 30
}

<div v-bind:style="styleObject"></div>

data: {
  styleObject: {
    color: 'red',
    fontSize: '13px'
  }
}