본문 바로가기
study/Vue.js

Vue.js CSS 클래스 바인딩

by 고기만두(개발자) 2022. 6. 10. 07:34
728x90
반응형

CSS 클래스를 저장해놓고 이를 불러와서 바인드하는 방법들이 다양하게 존재한다

<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14"></script>
    <style>
        .css1{
            background-color : yellow;
        }
        .css2{
            color : red;
        }
        .css3{
            background-color : red;
        }
        .css4{
            color : yellow;
        }
    </style>
    <script>
        window.onload = function(){
            var vm1 = new Vue({
                el : '#test1',
                data :{
                    css1Name : 'css1',
                    css2Name : 'css2',
                    isCss1 : false,
                    isCss2 : false

                },
                methods : {
                    setCss1 : function(){
                        this.css1Name = 'css3',
                        this.css2Name = 'css4'
                    },
                    setCss2 : function(){
                        this.isCss1 = true,
                        this.isCss2 = true
                    },
                    removeCss2 : function(){
                        this.isCss1 = false,
                        this.isCss2 = false
                    }
                }
            })
        }
    </script>
</head>
<body>
    <div id='test1'>
        <h3 class = 'css1 css2'>문자열</h3>
        <h3 v-bind:class='css1Name'>문자열</h3>
        <h3 v-bind:class='[css1Name,css2Name]'>문자열</h3>
        <button type='button' v-on:click='setCss1'>css1 변경</button>

        <h3 v-bind:class='{css1:isCss1, css2:isCss2}'>문자열</h3>
        <button type='button' v-on:click='setCss2'>css true 설정</button>
        <button type='button' v-on:click='removeCss2'>css false 설정</button>

        <h3 v-bind:class='[isCss1 ? css1Name : "", isCss2 ? css2Name : ""]'>문자열</h3> <!--2개 이상일 때는 쉼표로 구분, false면 "" true면 css1name으로 적용-->
    </div>
</body>
</html>

1. 쌩짜로 class = 꼴로 불러오기. 여러개 불러올 때는 띄어쓰기로 구분하기

2. data에 안에 css 클래스를 불러올 변수를 지정하고 그 변수로 v-bind:class 

여러개 불러올 때는 [css1Name,css2Name]꼴로 대괄호에서 쉼표로 구분하여 가져오자.

3. 메소드 안에 function으로 저장하여 특정 css name 을 지정하거나, 속성을 지정/해제할 수 있다. 

v-on:click 등을 통해 동적으로 이벤트를 먹일 수 있다.

+ 정규표현식으로도 지정할 수 있다!

 

vue.jsvue.js cssvue.js css 바인딩

css1을 css3으로, css2를 css4로 변경하는 이벤트

css bindingvue.js css bind

css 3,4로 변경된 후

css true/false 설정을 통해 온오프도 가능하다

728x90
반응형

댓글