Vue 데이터 바인딩-attribute/class/style
속성 데이터 바인딩
이미지의 src를 바인딩 해봄으로서 속성 바인딩 방법을 알아보자.
<template>
<div>
<img src="img/bee.png" />
</div>
</template>
프로젝트의 public 폴더에 img 폴더를 생성한 뒤 파일을 넣고 위와 같이 template안에 img 태그에 속성을 부여해주면 실행 시 이미지를 볼 수 있다.
데이터의 return 값에 src 객체를 넣어서 src속성을 바인딩해보자.
<template>
<div>
<img v-bind:src="bee" />
</div>
</template>
<script>
export default {
name: 'attrBinding',
components: {},
data() {
return {
bee: 'img/bee.png',
};
},
setup() {},
created() {},
mounted() {},
unmouted() {},
methods: {},
};
</script>
이번에는 input 값이 비었을 때 버튼을 disabled 시키는 방법에 대해 알아보자.
<input type="text" v-model="textValue" />
<button type="button" v-bind:disabled="textValue === ''">Click</button>
로직은 간단하다. 받아온 textValue값이 비었다면 버튼은 활성화 되지 않는다.
만약 v-bind:disabled=true 이면 버튼은 비활성화되고 v-bind:disabled=false 이면 버튼은 활성화된다.
데이터의 return에 아래와 같이 textValue객체를 추가해주자.
textValue: '',
프로그램을 실행시키면 처음에는 버튼이 비활성화 되었다가 입력을 하면 버튼이 활성화 되는 것을 볼 수 있다.
class에 데이터 바인딩
아래와 같이 코딩을 짜보자.
<template>
<div class="container">Class Binding</div>
</template>
<script>
export default {
name: 'classBinding',
components: {},
data() {
return {};
},
setup() {},
created() {},
mounted() {},
unmouted() {},
methods: {},
};
</script>
<style scoped>
.container {
width: 100%;
border: 1px dotted blue;
}
.active {
border: 1px solid red;
background: pink;
font-weight: bold;
}
.text-red {
color: red;
}
</style>
class 바인딩을 위해서는 v-bind:class="" 라는 속성을 사용한다.
v-bind:class는 기존에 가진 class에 바인딩된 클래스를 추가하는 속성이다.
<template>
<div class="container" v-bind:class="{ active: isActive, 'text-red': isRed }">
Class Binding
</div>
</template>
.
.
.
data() {
return {
isActive: true,
isRed: false,
};
},
위 코드를 실행해보면 isActive 라는 클래스는 적용 되지만 isRed 라는 클래스는 적용 되지 않은 것을 볼 수 있다.
클래스를 바인딩하는 또 다른 방법은 배열로 바인딩하는 것이다.
<template>
<div class="container" v-bind:class="[activeClass, redText]">
Class Binding
</div>
</template>
<script>
export default {
name: 'classBinding',
components: {},
data() {
return {
activeClass: 'active',
redClass: 'text-red',
};
},
이번에는 인라인 스타일을 활용한 스타일 바인딩을 배워보자. 스타일 바인딩을 할 때는 v-bind:style=""속성을 이용한다.
<div v-bind:style="styleObject">Style object</div>
.
.
.
data() {
return {
styleObject: {
backgroundColor: 'yellow',
color: 'green',
},
};
실행시 노란 바탕에 초록 글씨가 생기는 모습을 볼 수 있다. 인라인 스타일 역시도 객체 형태가 아닌 배열 형태로 사용 할 수 있다.
<div v-bind:style="[greenBorder, width100px]">Style object</div>
.
.
.
data() {
return {
greenBorder: 'border: 1px solid green',
width100px: 'width: 100px; height:100px;',
};
},
실행시 greenBorder의 스타일과 width100px의 스타일 모두 적용된다.
'개발 > Vue' 카테고리의 다른 글
Vue 이벤트 처리하기 - click/change/key (0) | 2022.04.17 |
---|---|
Vue 렌더링 (0) | 2022.04.17 |
Vue 데이터 바인딩-html/input/select (0) | 2022.04.16 |
Vue 컴포넌트 기초 (0) | 2022.04.13 |
Vue 라우터 (0) | 2022.04.13 |