VUE3
Vue3 - 클래스와 Style 바인딩
J-Chris
2023. 7. 10. 15:10
## HTML 클래스 바인딩
### 객체 바인딩
클래스를 동적으로 바인딩 하기 위해서는 :class(v-bind:class)를 사용할 수 있습니다.
<div>
class="text"
:class="{ active: isActive, 'text-danger': hasError }"
</div>
위 예시처럼 v-bind:class 디렉티브는 일반 class 속성과 공존할 수 있습니다.
그리고 객체를 반환하는 computed에 바인딩할 수도 있습니다.
<div class="text" :class="classObject"></div>
const classObject = computed(() => {
return {
active: isActive.value && !hasError.value,
'text-danger': !isActive.value && hasError.value,
};
});
### 배열에 바인딩
배열에 :class를 바인딩하여 클래스 목록을 적용할 수 있습니다.
<template>
<div :style="styleObject">
<div>Lorem ipsum dolor sit amet consectetur adipisicing elit.
Error voluptates deserunt fugiat quae sed doloremque ab odit dolore, quod reprehenderit quisquam perspiciatis architecto exercitationem iste,
beatae nobis amet, at facere!</div>
</div>
<button v-on:click="fontSize--">-</button>
<button v-on:click="fontSize++">+</button>
</template>
<script>
import { computed, reactive, ref } from 'vue';
export default {
setup () {
// const styleObject = reactive({
// color: 'red',
// fontSize: '13px',
// });
const fontSize = ref(13);
const styleObject = computed(() => {
return {
color: 'red',
fontSize: fontSize.value + 'px',
};
});
return { styleObject, fontSize };
}
}
</script>
<style lang="scss" scoped>
</style>