v-bind ๋๋ ํฐ๋ธ๋ฅผ ์ฌ์ฉํ ๋ class์ style์ ์ฌ์ฉํด ์ํ๋ ์คํ์ผ๋ง์ ํ ์ ์๋ค.
v-bind:class="ํด๋์ค๋ช
"
v-bind:class="{ ํด๋์ค๋ช
: ์กฐ๊ฑด }"
์์ฒ๋ผ v-bind:class๋ ๋ฌธ์์ด๊ณผ ๊ฐ์ฒด ๋๋ ๋ฐฐ์ด์ ๋ ๋ค ๋ฐ์ ์ ์๋ค.
๊ฐ์ฒด๋ฅผ ๋ฐ์ ๊ฒฝ์ฐ์๋ ํด๋์ค๋ช ์ ๊ฐ์ฒด์ ์์ฑ ํค์, ํด๋น ํด๋์ค๊ฐ ์ ์ฉ๋์ผ ํ๋ ์กฐ๊ฑด์ด ์์ฑ ๊ฐ์ผ๋ก ๋ค์ด๊ฐ๋ค.
1. ๊ฐ์ฒด ๊ตฌ๋ฌธ
1) v-bind ํด๋์ค ๋ฐ์ธ๋ฉ์ ์ด์ฉํ ํด๋์ค ํ ๊ธ
- ํด๋์ค๋ฅผ ๋์ ์ผ๋ก ํ ๊ธํ๊ธฐ ์ํด v-bind:class์ ๊ฐ์ฒด๋ฅผ ์ ๋ฌํ ์ ์๋ค.
- ์๋ ๊ตฌ๋ฌธ์ active ํด๋์ค์ ์กด์ฌ ์ฌ๋ถ๊ฐ ๋ฐ์ดํฐ ์์ฑ isActive์ ์ฐธ ์์ฑ์ ์ํด ๊ฒฐ์ ๋๋ค.
<div v-bind:class="{ active: isActive }"></div>
2) ์ฌ๋ฌ ํด๋์ค ํ ๊ธ
- ์ฌ๋ฌ ํด๋์ค๋ฅผ ํ ๊ธํ๋ ค๋ฉด ์๋ ์ฝ๋์ ๊ฐ์ด ๊ฐ์ฒด์ ํ๋๋ฅผ ์ถ๊ฐํ๋ฉด ๋๋ค.
- v-bind:class ๋๋ ํฐ๋ธ๋ ์ผ๋ฐ class์์ฑ๊ณผ ๊ณต์กดํ ์ ์๋ค.
<div
class="static"
v-bind:class="{ active: isActive, 'text-danger': hasError }"
></div>
data: {
isActive: true,
hasError: false
}
์ ์ฝ๋๋ ์๋์ ๊ฐ์ด ๋ ๋๋ง ๋๋ค.
<div class="static active"></div>
3)
๋ฐ์ธ๋ฉ ๋ ๊ฐ์ฒด๋ ์ธ๋ผ์ธ์ผ ํ์๋ ์๋ค.
<div v-bind:class="classObject"></div>โ
data: {
classObject: {
active: true,
'text-danger': false
}
}
4) computed์์ฑ ๋ฐ์ธ๋ฉ
๊ฐ์ฒด๋ฅผ ๋ฐํํ๋ 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'
}
}
}
2. ๋ฐฐ์ด ๊ตฌ๋ฌธ
1) ํด๋์ค ๋ชฉ๋ก์ ๋ฐฐ์ด๋ก ์ง์
๋ฐฐ์ด์ v-bind:class ์ ์ ๋ฌํ์ฌ ํด๋์ค ๋ชฉ๋ก์ ์ง์ ํ ์ ์๋ค.
<div v-bind:class="[activeClass, errorClass]"></div>
data: {
activeClass: 'active',
errorClass: 'text-danger'
}
์๋์ ๊ฐ์ด ๋ ๋๋ง ๋๋ค.
<div class="active text-danger"></div>
2) ์ผํญ ์ฐ์ฐ์๋ฅผ ์ด์ฉํ ํด๋์ค ํ ๊ธ
์ผํญ ์ฐ์ฐ์๋ฅผ ์ด์ฉํ์ฌ ๋ชฉ๋ก์ ์๋ ํด๋์ค๋ฅผ ์กฐ๊ฑด๋ถ ํ ๊ธํ ์ ์๋ค.
<div v-bind:class="[isActive ? activeClass : '', errorClass]"></div>
์์ ๊ฐ์ด ์ผํญ์ฐ์ฐ์๋ฅผ ์ด์ฉํ์ฌ ํด๋์ค๋ฅผ ํ ๊ธํ๋ฉด ํญ์ errorClass๋ฅผ ์ ์ฉํ๊ณ isActive๊ฐ true์ผ ๋๋ง activeClass๋ฅผ ์ ์ฉํ๋ค. ๊ทธ๋ฌ๋ ์ฌ๋ฌ ์กฐ๊ฑด๋ถ ํด๋์ค๊ฐ ์๋ ๊ฒฝ์ฐ ์ฅํฉํด์ง ์ ์๋ค. ๊ทธ๋์ ๋ฐฐ์ด ๊ตฌ๋ฌธ ๋ด์์ ๊ฐ์ฒด ๊ตฌ๋ฌธ์ ์ฌ์ฉํ์ฌ ์ฝ๋๋ฅผ ์ค์ผ ์ ์๋ค.
3) ๋ฐฐ์ด ๊ตฌ๋ฌธ ๋ด ๊ฐ์ฒด ๊ตฌ๋ฌธ์ ์ฌ์ฉํ์ฌ ํด๋์ค ํ ๊ธ
<div v-bind:class="[{ active: isActive }, errorClass]"></div>
3. ์ปดํฌ๋ํธ์ ํจ๊ป ์ฌ์ฉํ๋ ๋ฐฉ๋ฒ
์ฌ์ฉ์ ์ ์ ์ปดํฌ๋ํธ๋ก 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>
'๐ปWEB FrontEnd > ํ๋ ์์ํฌ Vue' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
์ฌ์ฌ์ฉ & ์ปดํฌ์ง์ (1) - ๋ฏน์ค์ธ (0) | 2021.02.26 |
---|---|
์ธ๋ผ์ธ ์คํ์ผ ๋ฐ์ธ๋ฉ (0) | 2021.02.25 |
v-model ๋ฐ์ธ๋ฉ (0) | 2021.02.25 |
CSR์ SSR์ ์ฅ๋จ์ (0) | 2021.02.08 |
vue์ ๋ฐ์์ฑ reactivity (0) | 2021.02.07 |