본문 바로가기

WEB Developer/Vue JS

v-bind 사용 - Dynamic Styling (Click 시 색상 변화)

 

 
 <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vue Basics</title>
    <link
      rel="stylesheet"
    />
    <link rel="stylesheet" href="styles.css" />
    <script src="https://unpkg.com/vue@3.4.9/dist/vue.global.js" defer></script>
    <script src="app.js" defer></script>
  </head>
  <body>
    <header>
      <h1>Vue Dynamic Styling</h1>
    </header>
    <section id="styling">
      <div
        class="demo"
        :class="{active: boxASelected}"
        @click="boxSelected('A')"
      ></div>
      <div
        class="demo"
        :class="{active: boxBSelected}"
        @click="boxSelected('B')"
      ></div>
      <div
        class="demo"
        :class="{active: boxCSelected}"
        @click="boxSelected('C')"
      ></div>
    </section>
  </body>
</html>

:class="{active: boxASelected}"

에서 boxASelected가 true이면 class=active, false이면 active가 제거됨

CSS에서 아래 속성을 추가하였으므로 class가 active가 되면 아래 CSS 속성이 동적으로 추가됨.

.
active {
  border-color: red;
  background-color: salmon;
}
 

 

 

Toggle 동작을 위해 아래와 같이 구현함.

 
 const app = Vue.createApp({
    data() {
        return {
            boxASelected: false,
            boxBSelected: false,
            boxCSelected: false
        };
    },
    methods: {
        boxSelected(box) {
            if (box === 'A') {
                this.boxASelected = !this.boxASelected;
            } else if (box === 'B' ) {
                this.boxBSelected = !this.boxBSelected;
            } else if (box === 'C') {
                this.boxCSelected = !this.boxCSelected;
            }
         }
    }
});

 app.mount('#styling');