Recent Posts
Recent Comments
«   2024/05   »
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
more
Today
Total
관리 메뉴

고리타분한 개발자

[Vue JS] Attribute and Class Binding 본문

Vue JS/Step By Step

[Vue JS] Attribute and Class Binding

sunlee334 2017. 12. 4. 17:04

이번 포스트에서는 제목과 같이 Attribute 와 Class 바인딩을 해볼 차례입니다. 우선 기본적인 button에 title을 주는 코드르 알아보도록 합시다.


<button title="I am the title of the button">Hover Over</button>


위와같이 입력후 버튼에 마우스를 가져다 대면, 저 글씨가 나오죠.

이번에는 Vue data에 binding 시켜보도록 하겠습니다.


<div id="root">
<button v-bind:title="title">Hover Over Me</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script>
<script>
var app = new Vue({
el: '#root',
data: {
title: 'Now the title is being set through JavaScript.'
},

})
</script>


이쯤되면 v-bind를 통해 vue data부분에있는 title을 바인딩 시켰다는 설명이 없어도 코드만으로 이해할 수 있으실거라 생각되어 집니다. 참고로 'v-bind:' 는 ':'로 대체할 수 있습니다. 위 코드에서 예를 들면, v-bind:title="title" 을 :title="title" 으로 쓸수 있죠. 

 

이번에는 class 바인딩을 해봅시다.


<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<title></title>
<style>
.color-red {
color: red;
}
</style>
</head>

<body>
<div id="root">
<h1 :class="className">Hello World</h1>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script>
<script>
var app = new Vue({
el: '#root',
data: {
className: 'color-red'
},

})
</script>
</body>

</html>


코드를 살펴보면, :class 를 통해 className을 바인딩 시켜주었습니다. className에는 color-red라는 style과 바인딩이 되어있고, style color-red는 red 효과를 주는 css 코드입니다. 이렇게되면, 'Hello World' 문구가 빨간색으로 변하게 되는것을 확인할 수 있습니다.

자, 이번에는 버튼에 이벤트를 주어볼까요? 아래는 버튼을 클릭하면 버튼이 빨간색으로 변화하는 코드입니다.


<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<title></title>
<style>
.is-loading {
background: red;
}
</style>
</head>

<body>
<div id="root">
<button :class="{'is-loading': isLoading}" @click="toggleClass">Toggle Me</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script>
<script>
var app = new Vue({
el: '#root',
data: {
isLoading: false
},
methods: {
toggleClass() {
this.isLoading = true;
}
}
})
</script>
</body>

</html>


isLoading에 false값을 줌으로써 default에는 background: red css값이 입혀지지 않게 만들었습니다. Vue methods부분을 보면 toggleClass함수는 isLoading을 true로 만들어 줍니다. 다시 버튼으로 돌아와서 @click 부분에 toggleClass를 바인딩 시켜줌으로써 버튼을 클릭하게되면 isLoading이 true가 되며, 버튼의 background color가 red로 변화하는 코드가 완성됩니다.

'Vue JS > Step By Step' 카테고리의 다른 글

[Vue JS] Components 101  (0) 2017.12.04
[Vue JS] The Need for Computed Properties  (0) 2017.12.04
[Vue JS] Vue Event Listeners  (0) 2017.12.04
[Vue JS] Lists  (0) 2017.11.30
[Vue JS] Vue Devtools  (0) 2017.11.30
Comments