[Vue] class와 style 바인딩

에구마·2023년 11월 21일
0

Vue

목록 보기
3/6

class 속성 바인딩

boolean 데이터를 사용해서 클래스 속성 지정 유무를 변경할 수 있다.

<body>
    <style>
      .title {
        font-size: 50px;
        color: blue;
      }
      .active {
        color: red;
      }
      .small {
        font-size: 30px;
      }
			.color--orange {
			  color: orange;
			}
    </style>
    <div id="app">
      <button @click="toggle">Toggle</button>
      <h1 :class="{active , 'title--small color--orange' : small}" class="title">
        {{msg}}
      </h1>
    </div>
    <script>
      const App = {
        data() {
          return {
            msg: "Hello Vue",
            isActive: false,
            isSmall: true,
          };
        },
        methods: {
          toggle() {
            this.isActive = !this.isActive;
          },
        },
      };
      const vm = Vue.createApp(App).mount("#app");
    </script>
  </body>

<h1 :class="{active , 'title--small color--orange' : small}" class="title">

이부분 에서 처럼, 하이픈(-)이 들어간 문자열이 클래스 명이면 따옴표’’ 로 감싸주어야 하고, 여러 클래스를 한번에 설정할 때에는 따옴표 안에서 띄어쓰기로 구분할 수 있다.

+) 배열을 사용해서 여러 클래스를 설정할 수도 있다.

<h1 :class="['active', 'title']">Hello Vue</h1>
  • 문자말고 데이터로 사용하려면
<div id="app">
  <h1 :class="[active, title]">Hello Vue</h1>
</div>
<script>
  const App = {
    data() {
      return {
        active: "active",
        title: "title",
      };
    },
  • 동적으로 바꾸려면
<div id="app">
  <h1 :class="[active, title]" @click="changeTitle">Hello Vue</h1>
</div>
<script>
  const App = {
    data() {
      return {
        active: "active",
        title: "title",
      };
    },
    computed: {},
    methods: {
      changeTitle() {
        this.title = "title--large";
      },
    },
  };
  • 또, 코드에서 보이듯이 속성의 값이 객체이다! 그럼 data()에 데이터로 선언할 수 있다.
<div id="app">
  <button @click="toggle">Toggle</button>
  <h1 :class="classObject" class="title">{{msg}}</h1> // 그 객체를 값으로 이용한다.
</div>
<script>
  const App = {
    data() {
      return {
        msg: "Hello Vue",
        active: false,
        small: true,
        classObject: { // 객체로 선언하고
          active: false,
          "title--small color--orange ": true,
        },
      };
    },
		methods: {
		  toggle() {
		    this.active = !this.active; 
		  },
		},

여기서 하나 문제, < button > 을 클릭하면 toggle()이 동작하는데, active라는 클래스가 추가되진 않는다.

왜 ? classObject에서 active의 값이 data의 active데이터를 참조하는게 아니라 그냥 false여서!

<div id="app">
  <button @click="toggle">Toggle</button>
  <h1 :class="classObject" class="title">{{msg}}</h1> //
</div>
<script>
  const App = {
    data() {
      return {
        msg: "Hello Vue",
        active: false,
        small: true,
      };
    },
    computed: {
      classObject() { //
        return {
          active: this.active,
          "title--small color--orange ": this.small,
        };
      },
    },
    methods: {
      toggle() {
        this.active = !this.active; // 
      },
    },
  };
  const vm = Vue.createApp(App).mount("#app");
</script>

“반응형 데이터에서 classObject가 갱신될 수 있어야 한다면, classObject는 계산된 데이터로 만들어져야합니다”




스타일 바인딩

데이터를 바인딩해서 동적으로 스타일을 제어하는 경우엔, 인라인으로 스타일을 지정하는 것을 권장한다. (일반 경우엔 권장하지 않음!)

<body>
  <div id="app">
    <h1 :style="`color: ${color}`">Hello Vue</h1> //보간 이용!
  </div>
  <script>
    const App = {
      data() {
        return {
          color: "red",
        };
      },
  • 이를 동적으로 사용할때
<body>
  <div id="app">
    <h1 :style="`color: ${color}`" @click="toBlue">Hello Vue</h1>
<!--혹은 <h1 :style="{color}" @click="toBlue">Hello Vue</h1> -->
  </div>
  <script>
    const App = {
      data() {
        return {
          color: "red",
        };
      },
      methods: {
        toBlue() {
          this.color = "blue";
        },
      },
    };
  • 여러개의 값도 가능하다
<body>
    <style>
      h1 {
        border: 4px solid;
      }
    </style>
    <div id="app">
      <h1
        :style="{color , width: `${width}px`}" // 쉼표로 구분!
        @click="toBlue(), increaseWidth()"    // click 핸들러의 경우 ()를 붙이고 쉼표로 구분
      >
        Hello Vue
      </h1>
    </div>
    <script>
      const App = {
        data() {
          return {
            color: "red",
            width: 200, // '200px'로 두면 후에 증감할때 번거로우니까!
          };
        },
        methods: {
          toBlue() {
            this.color = "blue";
          },
          increaseWidth() {
            this.width += 10;
          },
        },
      };
      const vm = Vue.createApp(App).mount("#app");
    </script>
  </body>

속성값 각각이 위에서처럼 원시타입이 아니고 객체면?

배열을 사용한다!

<div id="app">
  <h1 :style="[styleObject, titleStyleObject]">Hello Vue</h1> //
</div>
<script>
  const App = {
    data() {
      return {
        styleObject: {
          color: "cornsilk",
          backgroundColor: "royalblue",
        },
        titleStyleObject: {
          fontSize: "50px",
          fontWeight: "bold",
        },
      };
    },
  • computed를 사용하여 계산된 객체로 바꿔보자
<div id="app">
  <h1 :style="styleObject" @click="toBlue(); increaseWidth()">Hello Vue</h1>
</div>
<script>
  const App = {
    data() {
      return {
        color: "red",
        width: 200,
      };
    },
    computed: { ///
      styleObject() {
        return {
          color: this.color,
          width: this.width + "px",
        };
      },
    },
    methods: {
      toBlue() {
        this.color = "blue";
      },
      increaseWidth() {
        this.width += 50;
      },
    },
  };
	const vm = Vue.createApp(App).mount("#app");
</script>
profile
코딩하는 고구마 🍠 Life begins at the end of your comfort zone

0개의 댓글

관련 채용 정보