클래스와 인라인 스타일 바인딩하기

서진웅·2024년 2월 1일
post-thumbnail

클래스

1. 클래스를 동적으로 바인딩할 수 있다.

	<div class="textContent" :class="{ active: isActive, 'text-opacity': textOpacity }">
    	blah blah...
    </div>

이처럼 v-bind:class 디렉티브는 일반 class 속성과 공존할 수 있다.

2. 객체를 반환하는 computed속성과도 매핑할 수 있다.

	const classObj = computed(() => {
    	return {
        	active: isActive.value && !hasError.value,
            'text-danger': !isActive.value && hasError.value
        }
    })

3. 배열로도 바인딩할 수 있다.

	const activeClass = ref('active');
    const errorClass = ref('text-danger');
    
    <div :class="[activeClass, errorClass]"></div>

인라인 스타일 바인딩

1. 객체 형식으로 인라인 스타일에 바인딩할 수 있다.

	const activeColor = ref('red');
    const fontSize = ref(30);
    
    <div :style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>

하지만 코드가 깔끔해지게 스타일 객체로 따로 빼서 바인딩하는 것이 좋다.

	const styleObject = reactive({
    	color: 'red',
        fontSize: '13px'
    })
    
    <div :style="styleObject"></div>

2. 인라인 스타일 역시 배열로 바인딩할 수 있다.

	<div :style="[styleObj1, styleObj2]"></div>

0개의 댓글