class binding안됨

김민지·2022년 9월 5일

프론트

목록 보기
7/13
post-thumbnail
<!DOCTYPE html>
<html lang="ko">
<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>Vue Test</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.7.10/dist/vue.js"></script>
</head>
<body>
    <style>
        .active { 
            background-color: red;
        }
        .text-danger{
            font-size: 100px;
        }
    </style>
    <div id = "app" :class="classObject">
        안녕
    </div>
    <script>
        const vm = new Vue({
            el: '#app',
            data: {
                isActive : true,
                isText : true,
                classObject:{
                    'text-danger': true,
                    active : this.isActive
                   
                }
                
            }
        })
    </script>
</body>
</html>
  • isActive자리에 true를 넣으면 제대로 active효과가 적용이 되는데 this.isActive를 넣게 되면 적용이 되지 않는다
  • isActive 값도 true라고 출력이 되지만 style이 적용되지 않는다

하지만 다음과 같이 isActive하는 블럭과 isActive를 참조하는 블럭이 다른경우 제대로 출력된다

<!DOCTYPE html>
<html lang="ko">
<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>Vue Test</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.7.10/dist/vue.js"></script>
</head>
<body>
    <style>
        .active { 
            background-color: red;
        }
        .text-danger{
            font-size: 100px;
        }
    </style>
    <div id = "app" :class="classObject">
        안녕
    </div>
    <script>
        const vm = new Vue({
            el: '#app',
            data: {
                isActive : true,
                isText : true

                
            },
            computed: {
                classObject(){
                return{
                    'text-danger': true,
                    active : this.isActive
                }

                }
            }
        })
    </script>
</body>
</html>

해결법 - computed data사용

classObject:{
             'text-danger': true,
              active : [this.isActive]
}
profile
안녕하세요!

0개의 댓글