본문 바로가기
frontend/vue

[Hoon] Vuejs 강의 - 클래스와 스타일 바인딩

by 플로거 2020. 5. 7.

클래스와 스타일 바인딩

https://kr.vuejs.org/v2/guide/class-and-style.html

Vue는 class와 style에 v-bind를 사용할 때 특별히 향상된 기능을 제공합니다. 표현식은 문자열 이외에 객체 또는 배열을 이용할 수 있습니다.

HTML 클래스 바인딩하기

# 객체 구문

클래스를 동적으로 토글하기 위해 v-bind:class에 객체를 전달할 수 있습니다.

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id='app'>
	<div v-bind:class="{ active: isActive }">1</div> 
 </div>
new Vue({ el:'#app', data: { isActive: true } })

객체에 필드가 더 있으면 여러 클래스를 토글 할 수 있습니다. 또한v-bind:class 디렉티브는 일반 class 속성과 공존할 수 있습니다.

<div id='app'>
  <div class="static" v-bind:class="{ active: isActive, 'text-danger': hasError }">2</div>
</div>
new Vue({
    el:'#app',
    data: {            
        isActive: true,
        hasError: false
    }
})

아래와 같이 렌더링 됩니다

<div class="static active"></div>

바인딩 객체는 인라인 뿐 아니라, data object 나 computed 를 지원합니다.

<div v-bind:class="classObject">3</div>
new Vue({
    el:'#app',
    data: {  
        classObject: {
          active: true,
          'text-danger': false  
        }          
    }
})
new Vue({
    el:'#app',
    data: {  
        isActive: true,
        hasError: true,
    },
    computed: {
        classObject: function() {
            return {
                active : this.isActive,
                'text-danger' : this.hasError
            }
        }
    }
})

# 배열 구문

배열을 v-bind:class 에 전달하여 클래스 목록을 지정할 수 있습니다.

<div v-bind:class="[activeClass, errorClass]">4</div>
new Vue({
    el:'#app',
    data: {  
        activeClass: 'active',
        errorClass: 'text-danger'             
    }
})

아래와 같이 렌더링 됩니다

<div class="active text-danger">4</div>

조건부 토글하려면 삼항 연산자를 이용할 수 있습니다.

<div v-bind:class="[isActive ? activeClass : '', errorClass]">5</div>
new Vue({
    el:'#app',
    data: {  
        isActive : true,
        activeClass: 'active',
        errorClass: 'text-danger'             
    }
})

이것은 항상 errorClass를 적용하고 isActive가 true일 때만 activeClass를 적용합니다.

그러나 여러 조건부 클래스가 있는 경우 장황해질 수 있습니다. 그래서 배열 구문 내에서 객체 구문을 사용할 수 있습니다.

<div v-bind:class="[{ active: isActive }, errorClass]">6</div>

# 컴포넌트와 함께 사용하는 방법

사용자 정의 컴포넌트로 class 속성을 사용하면, 클래스가 컴포넌트의 루트 엘리먼트에 추가 됩니다. 이 엘리먼트는 기존 클래스는 덮어쓰지 않습니다.

<my-component class="baz boo"></my-component>
Vue.component('my-component', {
  template: '<p class="foo bar">Hi</p>'
})

결과:

<p class="foo bar baz boo">Hi</p>

클래스 바인딩

<my-component v-bind:class="{ active: isActive }"></my-component>
new Vue({
    el:'#app',
    data: {  
        isActive : true
    }
})

결과:

<p class="foo bar active">Hi</p>

인라인 스타일 바인딩

# 객체 구문

<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }">1</div>
new Vue({
    el:'#app',
    data: {  
        activeColor: 'red',
        fontSize: 30
    }
})

스타일 객체에 직접 바인딩 하여 템플릿이 더 간결하게

<div v-bind:style="styleObject">2</div>
new Vue({
    el:'#app',
    data: {
        styleObject: {
            color: 'red',
            fontSize: '23px'
        }
    }
})

# 배열 구문

v-bind:style에 배열 구문으로 같은 스타일의 엘리먼트에 여러 개의 스타일 객체를 사용할 수 있습니다.

<div v-bind:style="[baseStyles, addStyles]">3</div>
new Vue({
    el:'#app',
    data: {
        baseStyles: {
        	color: 'red'
        },
        addStyles : {
        	fontSize: '23px'
        }
    }
})

bit.ly/3fXOzon

 

인프런 인강 55%할인 쿠폰 - 커피한잔으로 Vue.js 핵심 강의!

인프런 인터넷 강의 55% 할인 쿠폰 - 커피한잔(5000원)으로 배우는 Vue.js 핵심 강의! 모바일 환경에서도 강의를 수강할 수 있도록 강의가 많이 개선되었습니다. 인프런 인터넷 강의 선착순 100명 55% �

plogger.tistory.com

bit.ly/2TtRHis

 

[Vue.js] Javascript Real 웹앱 개발 - 1부 : vue 개념 ~ 핵심 문법 - 인프런

이 강의를 수강하시면 Vue.js 와 관련된 기본적인 개념부터 Real 웹앱 개발을 해 볼 수 있습니다. 이 강의는 1부 기본기 이며, 2부와 3부를 통해서 실제 Real 웹앱을 구현해 보도록 하겠습니다. 초급 ��

www.inflearn.com

 

댓글