반응형
props: 부모와 자식간의 데이터 통신을 하며 사용자가 원하는 속성을 변경하는 script 속성
컴포넌트 코드(myBtn.vue)
text 부분은 text 속성을 이용해서 사용할 수 있고, slot을 사용하여 직접적으로 선언하여 설정할 수 있다.
<template>
<div
class="btn"
:style="{backgroundColor: color}"
:class="{large:large}">
<!-- Apple -->
<!-- {{ text }} -->
<slot></slot>
</div>
</template>
<script>
export default {
// component를 사용하는 쪽에서 색상을 변경할 수 있도록 설정
props: {
color: {
type: String,
default: 'gray'
},
large: {
type: Boolean,
default: false
},
// slot을 사용할 때에는 설정 안해도 된다.
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>
App.vue 코드
text 속성을 이용할 때에는 MyBtn에 text설정을 넣어줘야 하고
slot을 사용할 때에는 text 속성을 이용안해도 되고 외부에 적용해도 된다.
<template>
컴포넌트 사용:
<MyBtn text="Banana" />
<br />
사용자가 색상을 변경
<MyBtn
color="royalblue"
text="Banana" />
<br />
script에서 색상을 변경
<MyBtn
:color="color"
text="Banana" />
<br />
large 클래스를 추가
<MyBtn
large
text="Banana" />
<br />
<MyBtn :color="color">
<span style="color:red;">Banana</span>
</MyBtn>
</template>
<script>
// 컴포넌트 가져오기
import MyBtn from '~/components/MyBtn'
export default {
// 가져온 컴포넌트 연결
components: {
MyBtn
},
data(){
return {
color: '#000'
}
}
}
</script>
브라우저 확인
반응형
'프론트엔드 > Vue.js' 카테고리의 다른 글
컴포넌트 - Emit (0) | 2021.08.04 |
---|---|
컴포넌트 속성 상속 (0) | 2021.08.04 |
폼 입력 - 바인딩 (0) | 2021.08.02 |
이벤트 핸들링 - 키 수식어 (0) | 2021.08.02 |
이벤트 핸들링 - 이벤트 수식어 (0) | 2021.07.31 |