FrontEnd/Vue.js
[ Vue.js ] 조건부 css 적용하기 :class 사용하기
SangHoonE
2021. 12. 10. 17:35
Vue.js 에서 class에 변화를 주고 싶을 때 사용한다.
class태그의 변화는 data 객체에 있는 데이터의 변화로 인해 바뀌게 설정하는 것이 일반적이다.
<span
@click="changeStatus(index)"
class="pointer"
:class="{'text-danger fw-bold': task.status ==='to-do',
'text-warning': task.status === 'in-progress',
'text-success': task.status === 'finished'
}"
>
{{ firstCharUpper(task.status) }}
</span>
<script>
data () {
return {
availableStatuses: ['to-do', 'in-peogress', 'finished'],
tasks: [
{
name: 'Steal bananas from the stroe',
status: 'to-do'
}
}
},
methods: {
changeStatus(index){ //메서드명
let newIndex = this.availableStatuses.indexOf(this.tasks[index].status) // status의 index 파악 후 newIndex 할당
if(++newIndex > 2) newIndex = 0 // 만약 newIndex가 2초과시, newIndex = 0
this.tasks[index].status = this.availableStatuses[newIndex] // avaiableStatuses[] 배열의 내용 순차 입력
},
}
</script>
이렇게 span 태그를 클릭할 때마다 availableStatuses [] 내 내용이 순차적으로 span태그에 출력이 된다.
이럴 때, 해당 문구(availableStatuses[ ]) 에 따라서 class를 바꾸고 싶을 때 사용한다.
해당 내용은 글로 보기에는 난해한 부분이 있으므로,
직접 손으로 작성해나가면서 이해하는것이 좋다.
이상
- 조금 더 쉬운 예제를 가지고 오는건 어떨까 싶기도하다.
반응형