본문 바로가기

데일리 공부 기록

hands on vue - class들을 배열로 적용하기

728x90

1. 박스 세개를 생성한후 클릭시 색상이 변경되고 한번 더 클릭시 돌아오는 토클 기능

<!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
      href="https://fonts.googleapis.com/css2?family=Jost:wght@400;700&display=swap"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="styles.css" />
    <script src="https://unpkg.com/vue@next" defer></script>
    <script src="app.js" defer></script>
  </head>
  <body>
    <header>
      <h1>Vue Dynamic Styling</h1>
    </header>
    <section id="styling">
    	//이부분에서 class 적용을 배열로 함
      <div class="demo" v-bind:class="['demo', {active: boxASelected}]" v-on:click="selectedBox('A')"></div>
      <div class="demo" v-bind:class="['demo', {active: boxBSelected}]" v-on:click="selectedBox('B')"></div>
      <div class="demo" v-bind:class="['demo', {active: boxCSelected}]" v-on:click="selectedBox('C')"></div>
    </section>
  </body>
</html>
const app = Vue.createApp({
    data: function(){
        return{
            boxASelected: false,
            boxBSelected: false,
            boxCSelected: false,
        }
    },
    methods: {
        selectedBox(box){
            console.log('boxboxbox'); 
            console.log(box);
            if(box === 'A') {
                this.boxASelected = !this.boxASelected;
            } else if(box === 'B') {
                this.boxBSelected = !this.boxBSelected;
            } else if(box === 'C') {
                this.boxCSelected = !this.boxCSelected;
            }
        }
    },
    computed: {
        addActiveBoxA(){
            return {active: this.boxASelected};
        },
        addActiveBoxB(){
            return {active: this.boxBSelected};
        },
        addActiveBoxC(){
            return {active: this.boxCSelected};
        },
    },
    watch: {

    },
}).mount('#styling');