jiwoolee.space

Vuejs 개념 정리03 클래스와 스타일 바인딩-HTML클래스 바인딩하기 본문

Frontend-Vuejs

Vuejs 개념 정리03 클래스와 스타일 바인딩-HTML클래스 바인딩하기

jiwoolee 2021. 8. 18. 13:42

해당 게시글은 Vuejs Tutorial을 리뷰한 내용입니다. 

 

 

 

데이터 바인딩

엘리먼트의 클래스 목록인라인 스타일을 조작하기 위해 주로 사용

⇒ 두 속성은 v-bind로 처리 가능

⇒ 우리는 표현식으로 최종 문자열을 계산하면 됨

⇒ 문자열을 연결할 때 오류가 종종왕왕 발생함

⇒⇒ Vue는 class와 style에 v-bind를 사용할 때 특별히 향상된 기능 제공함

⇒⇒ 표현식은 문자열 이외에 객체 or 배열 이용 가능

 

 

 

 

 

1. Binding HTML classes

https://vueschool.io/lessons/vuejs-dynamic-classes?friend=vuejs 

 

Dynamic Classes - A Vue.js Lesson From our Vue.js Course: Vue.js...

A common need and use case for attribute bindings is to manipulate the look of elements through CSS classes or style attributes. To make this task easier than ever, Vue provides special...

vueschool.io

 

 

2. HTML 클래스 바인딩

 

  • 객체 구문

클래스를 동적으로 토글하기 위해 v-bind:class에 객체 전달 가능

 

<div v-bind:class="{active: isActive}"></div>

active클래스의 존재 여부가 데이터 속성 isActive의 참 속성에 의해 결정

 

 

객체에 필드가 더 있으면 여러 클래스를 토글 가능

v-bind:class 디렉티브는 일반 class 속성과 공존 가능

<div
  class="static"
  v-bind:class="{ active: isActive, 'text-danger': hasError }"
></div>
data: {
  isActive: true,
  hasError: false
}

//클래스 목록:  "static active"
//hasError가 True가 되면 클래스 목록: "static active text-danger"

 

 

 

근데,

바인딩된 객체는 인라인일 필요는 없다

 

 

 

<div v-bind:class="classObject"></div>
data: {
  classObject: {
    active: true,
    'text-danger': false
  }
}

같은 결과로 렌더링

 

 

 

 

 

객체를 반환하는 computed 속성에도 바인딩 가능

<div v-bind:class="classObject"></div>
data: {
  isActive: true,
  error: null
},
computed: {
  classObject: function () {
    return {
      active: this.isActive && !this.error,
      'text-danger': this.error && this.error.type === 'fatal'
    }
  }
}

 

 

 

 

 

  • 배열 구문

 

배열을 v-bind:class에 전달해 클래스 목록 지정 가능하다고 했음

그러니까,

<div v-bind:class="[activeClass, errorClass]"></div>
data: {
  activeClass: 'active',
  errorClass: 'text-danger'
}

라면,

 

 

 

<div class="active text-danger"></div>

이렇게 렌더링된다는 거다.

 

 

 

 

 

목록에 있는 클래스를 조건부 토글하면,

삼향 연산자 이용

예를 들어,

<!--
항상 errorClass 적용하고 
isActive가 true일 때만 activeClass를 적용
-->

<div v-bind:class="[isActive ? activeClass : '', errorClass]"></div>

 

 

 

 

 

여러 조건부 클래스가 있는 경우 복잡해질 수도

⇒ 배열 구문 내에서 객체 구문 사용 가능

<div v-bind:class="[{ active: isActive }, errorClass]"></div>

 

 

 

 

 

 

 

 

 

  • 컴포넌트와 함께 사용하는 방법

vue component를 안다면 읽자

더보기

 

 

사용자 정의 컴포넌트로 class 속성을 사용하면,

클래스가 컴포넌트의 루트 엘리먼트에 추가

이 엘리먼트는 기존 클래스는 덮어쓰지 않는다

 

 

 

 

 

 

예를 들어,

Vue.component('my-component', {
  template: '<p class="foo bar">Hi</p>'
})

 이런 컴포넌트를 선언하는 경우

사용할 클래스 일부를 추가하면

<my-component class="baz boo"></my-component>

 

렌더링 된 HTML은

<p class="foo bar baz boo">Hi</p>

 

클래스 바인딩도 동일하다

<my-component v-bind:class="{ active: isActive }"></my-component>

 

 

isActive가 참일 때 렌더링 된 HTML은

<p class="foo bar active">Hi</p>

이렇게 된다.

 

 

 

 

 

나는 이 예시가 잘 이해가 되지 않았는데 다음 예시는 이해하기 좋았다

 

사용자 정의 컴포넌트에서 class 속성을 사용하면,

컴포넌트의 루트 엘리먼트에 class가 추가된다

이렇게,

<div id="app">
<Child class="baz boo"> </Child> 
</div>
const Child = { 
	template: '<div class="foo bar">Child</div>', } 


new Vue({ 
	el: '#app', 
    components: { Child } });

 그러면,

<Child /> <div class="foo bar baz boo">Child</div>로 랜더링되겠지

 

 

 


:class 바인딩도 동일하게 사용할 수 있다

<div id="app"> 
<Child :class="{ active: isActive }"></Child> 
</div>
const Child = { 
template: '<div class="foo bar">Child</div>', } 

new Vue({ 
	el: '#app', 
    data: { isActive: true }, 
    components: { Child } });

그러면,

isActive true 일 경우, <div class="foo bar active">Child</div>로 랜더링되겠지

 



출처: https://beomy.tistory.com/50 

 

 

 

 

 

 

 

 

 

 

** vue component가 무엇이냐

Vujs ComponentHTML Element를 확장하고 재사용 가능한 형태로 구현한다. Vuejs에서 사용된 모든 컴포넌트는 Vuejs의 인스턴스이기도 하다. 컴포넌트의 생성은 등록 -> 사용 패턴으로만 이루어진다.

이 과정은 지난 게시글을 차례로 확인하자