본문 바로가기

WEB Developer/Vue JS

computed 속성 사용: Dynamic Styling (Click 시 색상 변화)

computed 속성을 사용하여 적용이 가능하다.

 

<!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="boxAClasses"
        @click="boxSelected('A')"
      ></div>
      <div
        class="demo"
        :class="boxBClasses"
        @click="boxSelected('B')"
      ></div>
      <div
        class="demo"
        :class="boxCClasses"
        @click="boxSelected('C')"
      ></div>
    </section>
  </body>
</html>

 

아래는 app.js 코드

const app = Vue.createApp({
    data() {
        return {
            boxASelected: false,
            boxBSelected: false,
            boxCSelected: false
        };
    },
    computed: {
        boxAClasses () {
            return { active: this.boxASelected };
        },
        boxBClasses () {
            return { active: this.boxBSelected };
        },
        boxCClasses () {
            return { active: this.boxCSelected };
        },

    },
    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');

 

또는..

 
 <!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', {active: boxASelected}]"
        @click="boxSelected('A')"
      ></div>
      <div
        :class="['demo', {active: boxBSelected}]"
        @click="boxSelected('B')"
      ></div>
      <div
        :class="['demo', {active: boxCSelected}]"
        @click="boxSelected('C')"
      ></div>
    </section>
  </body>
 </html>

 

으로 구성할 수 도 있다.