본문 바로가기
Vue/데이터 바인딩

클래스와 스타일에 데이터 바인딩(class, style)

by BAYABA 2021. 9. 18.
  1. 개인 공부 목적으로 작성한 글입니다.
  2. 아래 출처를 참고하여 작성하였습니다.

Intro

  1. html의 디자인을 담당하고 있는 class와 style 태그에 대한 데이터 바인딩을 다루는 방법입니다.

1. class


1-1. 클래스 처리 기본 방법

  1. v-bind:class를 사용하면 기존 class 속성에 add가 됩니다.
  2. 'active': isActive를 true라고 주고, 'text-red':isRed을 false라고 주게 되면
    • 'active' 속성이 class에 적용이 됩니다.
    • 'text-red' 속성은 class에 적용되지 않습니다.
<template>
    <div class="container" v-bind:class="{'active':isActive, 'text-red':isRed}">Class Binding</div>
</template>
<script>
export default {
    name: '',
    comments: {},
    data() {
        return {
            isActive: true,
            isRed: false
        };
    }
}
</script>
<style scoped>
.container {
    width: 100%;
    height: 200px;
}

.active {
    background-color: yellow;
    font-weight: bold;
}

.text-red {
    color: red;
}
</style>


1-2. 배열을 이용해서 클래스를 처리하는 방법

  1. 배열을 사용해서 커스텀하고자 하는 여러 속성을 한 번에 적용할 수 있습니다.
<template>
    <div class="container" v-bind:class="[activeClass, redClass]">Class Binding</div>
</template>
<script>
export default {
    name: '',
    comments: {},
    data() {
        return {
            activeClass: 'active',
            redClass: 'text-red',
        };
    }
}
</script>
<style scoped>
.container {
    width: 100%;
    height: 200px;
}

.active {
    background-color: yellow;
    font-weight: bold;
}

.text-red {
    color: red;
}
</style>


2. style


2-1. Style 처리 기본 방법 (Object로 바인딩하는 방법)

  1. inline 스타일로 바인딩할 때 주의할 점은 key값을 카멜케이스로 작성해줘야 합니다.
<template>
    <div v-bind:style="styleObject">인라인 스타일 Binding</div>
</template>
<script>
export default {
    name: '',
    comments: {},
    data() {
        return {
            styleObject: {
                backgroundColor: 'yellow',
                color: 'red',
                fontWeight: 'bold'
            }
        };
    }
}
</script>
<style scoped>
.container {
    width: 100%;
    height: 200px;
}

.active {
    background-color: yellow;
    font-weight: bold;
}

.text-red {
    color: red;
}
</style>


2-2. 배열을 이용해서 Style을 처리하는 방법

  1. 배열을 사용해서 커스텀하고자 하는 여러 속성을 한 번에 적용할 수 있습니다.
<template>
    <div v-bind:style="[baseStyle, addStyle]">인라인 스타일 Binding</div>
</template>
<script>
export default {
    name: '',
    comments: {},
    data() {
        return {
            baseStyle: 'background-color:yellow;width:100%;height:200px;',
            addStyle: 'color:red;font-weight:bold;'
        };
    }
}
</script>
<style scoped>
.container {
    width: 100%;
    height: 200px;
}

.active {
    background-color: yellow;
    font-weight: bold;
}

.text-red {
    color: red;
}
</style>


출처

  1. Vue.js 제대로 배워볼래?(Vue.js 프로젝트 투입 일주일 전)