클래스와 스타일 바인딩

토리최고·2022년 1월 16일
0

Vue 문법

목록 보기
7/20
post-thumbnail
<template>
  <!-- 클래스라는 속성이 데이터를 취급할 수 있도록 바인딩 필요 -->
  <h1
    :class="{ active: isActive}"
    @click="activate">
    Hello?! ({{ isActive }})
  </h1>
</template>

<script>
export default {
  data() {
    return {
      isActive: false
    }
  },
  methods: {
    activate() {
      this.isActive = true
    }
  }
}
</script>

<style scoped>
/* scoped 는 app.vue 아니면 다른곳에 적용 안됨 */
  .active {
    color: red;
    font-weight: bold;
  }
</style>

active라는 class를 추가하는데, true일때만 동작

관련 공식 문서:
https://v3.ko.vuejs.org/guide/class-and-style.html#html-%E1%84%8F%E1%85%B3%E1%86%AF%E1%84%85%E1%85%A2%E1%84%89%E1%85%B3-%E1%84%87%E1%85%A1%E1%84%8B%E1%85%B5%E1%86%AB%E1%84%83%E1%85%B5%E1%86%BC

<template>
  <h1
    :style="{
      color,
      fontSize,
    }"
    @click="changeStyle">
    Hello?!
  </h1>
</template>

<script>
export default {
  data() {
    return {
      color: 'orange',
      fontSize: '30px'
    }
  },
  methods: {
    changeStyle() {
      this.color = 'red'
    }
  }
}
</script>

<style>

</style>

데이터를 동적으로 관리할 수 있다.

<template>
  <h1
    :style="[fontStyle, backgroundStyle]"
    @click="changeStyle">
    Hello?!
  </h1>
</template>

<script>
export default {
  data() {
    return {
      fontStyle: {
        color: 'orange',
        fontSize: '30px'
      },
      backgroundStyle: {
        backgroundColor: 'black'
      }
    }
  },
  methods: {
    changeStyle() {
      this.fontStyle.color = 'red'
      this.fontStyle.fontSize = '50px'
    }
  }
}
</script>

<style>

</style>

기본적으로 객체데이터로 연결하지만 여러가지 객체데이터를 연결할때는 배열데이터로 활용할수도있다.

0개의 댓글

관련 채용 정보