1. 컴포넌트
Vue.js 컴포넌트는 Vue 애플리케이션의 재사용 가능한 코드 조각으로, 각각의 컴포넌트는 독립적인 뷰 및 로직을 가집니다. 컴포넌트는 더 큰 애플리케이션을 작은, 관리 가능한 부분으로 나누어 개발할 수 있게 해 줍니다.
2. components와 props
- props: 부모 컴포넌트로부터 데이터를 전달받기 위한 속성을 정의합니다.
// App.vue
<template>
<h2>Slot 미사용</h2>
<MyBtn color="royalblue" text="Banana" />
<MyBtn color="#000" text="Apple" />
<MyBtn v-bind:color="color" text="Cherry" />
<MyBtn large color="royalblue" text="Melon" />
<h2>Slot 사용</h2>
<MyBtn2 color="royalblue">Banana</MyBtn2>
<MyBtn2 color="#000">Apple</MyBtn2>
<MyBtn2 v-bind:color="color">Cherry</MyBtn2>
<MyBtn2 large color="royalblue">Melon</MyBtn2>
<MyBtn2 large color="royalblue">
<span style="color: red">Melon</span>
</MyBtn2>
</template>
<script>
import MyBtn from './components/MyBtn.vue';
import MyBtn2 from './components/MyBtn2.vue';
export default {
components: {
MyBtn,
MyBtn2,
},
data() {
return {
color: 'orange',
};
},
};
</script>
// MyBtn.vue
<template>
<div
v-bind:class="{large: large}"
v-bind:style="{backgroundColor: color}"
class="btn">
{{ text }}
</div>
</template>
<script>
export default {
props: {
color: {
type: String,
default: 'gray',
},
large: {
type: Boolean,
default: false,
},
text: {
type: String,
default: '',
},
},
};
</script>
<style scoped lang="scss">
.btn {
display: inline-block;
margin: 4px;
padding: 6px 12px;
border-radius: 4px;
background-color: gray;
color: white;
cursor: pointer;
&.large {
font-size: 20px;
padding: 10px 20px;
}
}
</style>
// MyBtn2.vue
<template>
<div
v-bind:class="{large: large}"
v-bind:style="{backgroundColor: color}"
class="btn">
<slot></slot>
</div>
</template>
<script>
export default {
props: {
color: {
type: String,
default: 'gray',
},
large: {
type: Boolean,
default: false,
},
},
};
</script>
<style scoped lang="scss">
.btn {
display: inline-block;
margin: 4px;
padding: 6px 12px;
border-radius: 4px;
background-color: gray;
color: white;
cursor: pointer;
&.large {
font-size: 20px;
padding: 10px 20px;
}
}
</style>
Slot 미사용
Banana
Apple
Cherry
Melon
Slot 사용
Banana
Apple
Cherry
Melon
Melon
위 코드는 props를 통해 MyBtn, MyBtn2 컴포넌트를 조작하는 코드입니다.
slot 미사용 부분은 props를 부모 컴포넌트 data 속성의 값을 바인딩하여 자식 컴포넌트로 전해줄 수 도 있고 자식 컴포넌트에 props로 선언한 large를 컴포넌트를 호출할 때 명시 여부에 따라 처리할 수도 있습니다.
slot 사용 부분은 자식 컴포넌트에 <slot></slot> 태그를 달아 미사용 부분처럼 text props를 내려주는 대신 컴포넌트 MyBtn2를 <></> 형식으로 표시하여 그 안에 원하는 텍스트나 태그를 생성하여 쓸 수 있습니다. 생성한 태그에는 마찬가지로 style부분을 인라인 형식이나 데이터를 바인딩하여 넘겨줄 수 있습니다.
관련 문서:
'Front-end > Vue' 카테고리의 다른 글
Vue.js) 컴포넌트 - Emit (0) | 2024.07.30 |
---|---|
Vue.js) 컴포넌트 - 속성 상속 (2) | 2024.07.29 |
Vue.js) v-model 수식어 (0) | 2024.07.29 |
Vue.js) 폼 입력 바인딩 (1) | 2024.07.29 |
Vue.js) 이벤트 핸들링-키 수식어 (1) | 2024.07.26 |