Vue js dynamic class 적용
사용자의 입력에따라 css class를 다르게(동적으로) 적용하는 방법을 공유해봅니다.
:class를 이용하기
<template>
<div class="hello">
<h3
:class="{'option-first': this.flag, 'option-second': !this.flag}"
>class 동적으로 적용하기!</h3>
<button @click="changeClass(flag)">
Class Toggle
</button>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App',
flag: true
}
},
methods: {
changeClass: function(flag){
this.flag = !flag;
}
}
}
</script>
<style scoped>
.option-first {
color: red;
}
.option-second {
color: blue;
}
</style>
:class
는 v-bind:class
의 줄임표현입니다. 대부분의 속성(태그)앞에 :
을 붙이면 해당 Component내에 있는 변수 혹은 함수를 바인딩시킬 수 있습니다.
:class="{'option-first': this.flag, 'option-second': !this.flag}"
이부분이 동적으로 클래스를 적용하는 핵심인데 아주 간단합니다. {'작성한 클래스명' : boolean type}
으로 작성해주시면 됩니다.
음 추가적으로 작성한 클래스명이 -
혹은 _
으로 구분이 되어있으면 반드시 ''(작은따옴표)
로 감싸줘야 합니다. 그렇지 않고 단순히 한 단어로 이루어져있으면 ''로 감쌀 필요가 없습니다. (ex: {header: true}
)
지금은 flag
라는 변수에 바인딩을 걸어 두었지만 보틍은 v-for문으로 반복문을 사용할 때 index를 이용하여 많이 사용합니다. 요부분은 아래에서 다루도록 하죠
v-for의 index 활용하기
<template>
<div class="hello">
<div
v-for="(data, index) in dummyData"
:class="{'option-first': index === 0, 'option-second': data === 'test2'}">
{{ data }}
</div>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App',
dummyData: ["test1", "test2", "test3", "test4", "test5", "test6"]
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.option-first {
color: red;
}
.option-second {
color: blue;
}
</style>
v-for문
을 사용하여 반복문을 작성할 때 v-for="(data, index) in dummyData"
이렇게 만들면 index
값이 생성이됩니다. 이 index
를 활용하여 :class
의 boolean
자리에 조건문을 걸어주시는 방식으로 작성하면 아주 편합니다.
'Front_End > Vue.js' 카테고리의 다른 글
04. Vue.js 스타일 적용 방법 (0) | 2017.12.26 |
---|---|
03. Vue.js 초간단 Event Handling (1) | 2017.12.25 |
02. Vue.js Vue 인스턴스 옵션 and Life Cycle (0) | 2017.12.24 |
01. Vue.js 기본기: 각종 디렉티브 (0) | 2017.12.23 |
00. Vue.js 설치와 시작 (2) | 2017.12.22 |