본문 바로가기
FrontEnd/Vue 2

[Vue.js] Computed 속성을 활용한 CSS Class 바인딩

by Chaedie 2022. 9. 18.
728x90

Computed 속성을 활용한 CSS Class 바인딩

  • 주석 처리 한 것처럼 class 네임에 인라인으로 warning을 true일 때만 넣어줄 수가 있다.
  • computed 속성을 활용하면 인라인이 아니라 하나의 함수명으로 제어할 수 있다.
<!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>
      .warning {
        color: red;
      }
    </style>
  </head>
  <body>
    <div id="app">
      <!-- <p v-bind:class="{ warning: isError }">Hello</p> -->
      <p v-bind:class="errorTextColor">Hello</p>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <script>
      new Vue({
        el: '#app',
        data: {
          isError: false,
        },
        computed: {
          errorTextColor: function () {
            return this.isError ? 'warning' : null;
          },
        },
      });
    </script>
  </body>
</html>

댓글