본문 바로가기

Vue.js

Kossie Coder 08. 클래스 & 스타일 바인딩

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .red {
            color: red;
        }
        .bold {
            font-weight: bold;
        }
        .font-bold {
            font-weight: bold;
        }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <div :class="{red:isRed, bold:isBold}">Hello</div> <!--binding을 위해 class앞에 :을 붙여준다. 2개의 class를 적용시키고싶으면 ,를 넣으면 된다.-->
        <div :class="{'font-bold':isBold}">Hello</div> <!--class명에 -가 있으면 ''로 묶어줘야한다.-->
        <div :style="{ color: red, fontSize: size}">Hello</div>  <!--color는 한 단어이므로 color로 적으면 되는데, font-size는 -대신 S로 바꾼다. -->
        <button @click="update">Click</button> <!--버튼클릭시, isRed&isBold값 변경된다.-->
    </div>

<script>
   new Vue({
      el: '#app',
      data: { 
          isRed: false,
          isBold: false,
          red: 'red',
          size: '30px'
      },
      methods: {
        update(){ 
              this.isRed = !this.isRed;
              this.isBold = !this.isBold;
          }
      },
      computed: {},
      watch: {}
})
</script>
</body>
</html>

1. 클래스 바인딩하기

1/ 객체 구문

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

이 경우, active 클래스의 존재여부는 isActive의 true/false값에 의해 결정된다.

 

class가 여러개면 여러 클래스를 ,와 함께 적을 수 있다.

<div
  class="static"
  v-bind:class="{ active: isActive, 'text-danger': hasError }"
></div>
<!--class명에 -가 있으면 '로 묶어줘야한다.-->
data: {
  isActive: true,
  hasError: false
}

 

아래와 같이 랜더링된다.

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