본문 바로가기
Dev.FrontEnd/Vue

[Vue] class 동적 바인딩

by superpil 2020. 11. 4.

목차

Class 동적 바인딩


Vue로 Front 개발을 하다 보면 동적으로 Class를 추가 또는 삭제를 해야 될 때가 있다.

JQuery는 잘모르지만 JQuery에서 addClass(), removeClass()와 비슷한 개념 이다.

딱히 어렵지 않아 예제를 보면 쉽게 이해할 수 있다.

 

문법


:class="{ '클래스이름' : '조건' }"

조건이 true경우 클래스이름이 바인딩 되고 false경우 바인딩된 클래스이름이 제거 된다.

 

기초 사용법


<template>
  <div>
    <h1 :class="{ red: isBind }">Class Bind</h1>
    <button @click="setBind">바인딩</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isBind: false,
    };
  },
  methods: {
    setBind() {
      this.isBind = !this.isBind;
    },
  },
};
</script>

<style scoped>
.red {
  color: red;
}
</style>

👉 <h1 :class="{ red: isBind }">

  1. isBind값이 true경우 red클래스가 바인딩 되어 스타일이 적용되고 false경우 red클래스가 바인딩에서 해제되어 적용된 스타일이 사라진다.
  2. red는 아래 style에 정의 되어 있다.

 

👉 <button @click="setBind">

  1. 버튼을 클릭하면 setBind()가 실행된다.
  2. isBind를 조작하기 위한 버튼이다.

 

👉 this.isBind = !this.isBind

  1. isBind의 값을 true경우 falsefalse경우 true로 변경하는 토클형태로 컨트롤한다.

 

고급 사용법


반복문에서 특정 조건에 Class 바인딩

<template>
  <div>
    <h1
      v-for="item in forDatas"
      :key="item.id"
      :class="{ red: item.id === '4' }"
    >
      {{ item.name }}
    </h1>
  </div>
</template>

<script>
export default {
  data() {
    return {
      forDatas: [
        { id: "1", name: "super" },
        { id: "2", name: "pil" },
        { id: "3", name: "hello" },
        { id: "4", name: "world" },
      ],
    };
  },
};
</script>

<style scoped>
.red {
  color: red;
}
</style>

👉 :class="{ red: item.id === '4' }"

  1. forDatas를 반복하면서 id값이 4인 경우 red클래스를 바인딩 한다.
  2. Class바인딩은 조건의 결과값이 true이면 바인딩 되기 때문에 item.id === '4' 조건식 이외에도 다양한 조건으로 바인딩 할 수 있다.

 

If문 Class 바인딩

<template>
  <div>
    <h1 :class="[textColor === 'pinkText' ? 'pink' : 'blue']">Super Pil</h1>
    <button @click="changeColor">색상변경</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      textColor: "pinkText",
    };
  },
  methods: {
    changeColor() {
      if (this.textColor === "pinkText") {
        this.textColor = "blueText";
      } else {
        this.textColor = "pinkText";
      }
    },
  },
};
</script>

<style scoped>
.pink {
  color: pink;
}
.blue {
  color: blue;
}
</style>

👉 <h1 :class="[textColor === 'pinkText' ? 'pink' : 'blue']">

  1. textColor값이 pinkText경우 pink클래스를 바인딩하고 그 외 다른 값일 경우 blue클래스명을 바인딩 한다.

 

👉 <button @click="changeColor">

  1. 버튼을 클릭 시 changeColor()가 실행되고 textColor값을 토클방식으로 변경한다.

 

다수 클래스 바인딩

동적으로 각각 다른 조건으로 클래스를 바인딩 하고 싶을 경우가 있다.

기초 사용법처럼 각각의 클래스는 객체로 구분하고 배열로 감싸면 된다.

아래 예제를 보면 쉽게 이해 할 수 있다.

 

<template>
  <div>
    <p :class="[{ blue: isBlue }, { bold: isBold }]">Super Pil</p>
    <button @click="changeColor">색상변경</button>
    <button @click="changeBold">Bold변경</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isBlue: false,
      isBold: false,
    };
  },
  methods: {
    changeColor() {
      this.isBlue = !this.isBlue;
    },
    changeBold() {
      this.isBold = !this.isBold;
    },
  },
};
</script>

<style scoped>
.blue {
  color: blue;
}
.bold {
  font-weight: bold;
}
</style>

👉 <p :class="[{ blue: isBlue }, { bold: isBold }]">

  1. bluebold는 각각 다른 조건에 의해 클래스가 바인딩 된다. blueisBlue의 값이 true경우 바인딩되고 boldisBoldtrue경우 바인딩 된다.

 

👉 <button @click="changeColor">

👉 <button @click="changeBold">

  1. 각각의 메소드는 text의 색상과 굵기를 변경한다.

 

이 정도만 알면 개발하면서 Class조작하는데는 무리 없을 듯 하다.

대체로 기초 사용법만 알아도 개발하는데 문제는 없지만 가끔 If문으로 Class를 바인딩 하거나 다수의 바인딩이 필요할 때가 있어 추가적으로 공부 했다.

분명 또 다른 바인딩 방법이 있을거다. 그건 필요시 추가로 알아보자.

 

잘못된 내용이나 보충이 필요한 내용이 있다면 댓글 남겨 주세요!

주니어 개발자에게 큰 도움이 됩니다! 감사합니다! 😃

 

Reference


  1. 클래스와 스타일 바인딩 - Vue.js -Vue Class 바인딩

댓글