Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 | 31 |
Tags
- 머신러닝종류
- SSAFY
- 리액트
- SSAFYcial
- queryset
- git
- js
- db
- vitepwa
- 알고리즘
- TypeScript
- 백준
- 14658
- QuerySetAPI
- 싸피셜
- PWA
- Python
- 싸피
- 데코레이터
- 플로이드워셜
- Javascript
- SQL
- sqld
- pwa적용하기
- Django
- 셀프넘버
- 싸피10기
- unionfind
- VITE
- react
Archives
- Today
- Total
Meme's IT
[Vue] v-bind (Attribute, Class, Style) 본문
# v-bind란?
하나 이상의 속성 또는 컴포넌트 데이터를 표현식에 동적으로 바인딩
1. Attiribute Bindings
<img v-bind:src="imageSrc" alt="#">
<a v-bind:href="myUrl">link</a>
<img :src="imageSrc" alt="#">
<a :href="myUrl">link</a>
- v-bind:에서 :만 써도 된다.
- Dynamic attribute name(동적 인자 이름)
- 대괄호로 감싸서 directive argument에 JavaScript 표현식을 사용할 수도 있음
- JavaScript 표현식에 따라 동적으로 평가된 값이 최종 argument값으로 사용됨
<p :[dynamicattr]="dynamicValue">....</p>
...
const dynamicattr = ref('title') // 여기 카멜케이스 안됨 다 소문자로
const dynamicValue = ref('Hello')
2. Class & Style Bindings
class와 style도 속성이므로 v-bind를 사용해서 동적으로 문자열 값 할당 가능
하지만 번거롭고 오류가 발생하기 쉽다
→ 클래스와 스타일에는 객체 or 배열을 활용해서 가능
# Class Binding
🔹 Class - 객체로 활용하기
(1) 한개만 해보기
style에 있는 class를 넣어줄 때, v-bind를 이용
.active {
color: crimson;
}
해당 클래스에
const isActive = ref(true)
return {
isActive
}
활성 / 비활성을 제어할 것을
<div :class="{ active: isActive }">Text</div>
객체로 넣어준다
(2) 여러개 넣기
객체이므로 여러개도 가능
<div class="static" :class="{ active : isActive, 'text-primary': hasInfo}">Text</div>
이런식으로 기존에 있던 class에 추가로 v-bind 클래스도 추가 가능함
근데, inline으로 하니까 너무 길어지네?
→ 밑으로 빼줄 수 있음
(3) 객체 한번에 넣기 → 유지보수 굿
const classObj = ref({
active : isActive,
'text-primary': hasInfo
})
이런식으로 정의를 해주고
<div class="static" :class="classObj">Text</div>
한번에 넣기 가능
🔹 Class - 배열로 활용하기
const activeClass = ref('active')
const infoClass = ref('text-primary')
이런식으로 정의를 해주고
<div :class="[activeClass, infoClass]">Text</div>
배열로 넣어주기
그리고, 배열이므로 배열 안에 객체가 들어갈 수 있음
<div :class="[{active : isActive}, infoClass]">Text</div>
# Style Binding
🔹 Style - 객체로 활용하기
const activeColor = ref('crimson')
const fontSize = ref(50)
우선 넣어주기 위해 스타일을 만들어 주고
<div :style="{ color:activeColor, fontSize:fontSize+'px'}">Text</div>
이런식으로 적용 가능
물론 얘도
const styleObj = ref({
color:activeColor,
fontSize:fontSize.value +'px' // 여기서는 .value쓰는거 조심
})
이렇게 객체를 미리 만들어 놓고
<div :style="styleObj">Text</div>
한번에 가능
더보기
ref 객체가 최종 결과물이면 자동으로 unwrap이 되는데
최종 결과물이 아니라면 .value해줘야함
🔹 Style - 배열로 활용하기
const styleObj = ref({
color:activeColor,
fontSize:fontSize+'px'
})
const styleObj2 = ref({
color: 'blue',
border: '1px solid black'
})
이런식으로 객체 두개 만들어 두고
<div :style="[styleObj, styleObj2]">Text</div>
배열로 넣어줄 수 있음
더 자세한 사항은 공식문서
'FrontEnd > Vue' 카테고리의 다른 글
[Vue] Form Input Bindings (0) | 2023.11.02 |
---|---|
[Vue] v-on (0) | 2023.11.02 |
[Vue] Directive (0) | 2023.11.02 |
[Vue] Template Syntax (0) | 2023.11.02 |
[Vue] Vue의 기본 구조 (0) | 2023.11.01 |