props


https://ryuzuka.github.io/VUE/tutorial/08_props.html


  • props

 Vue.js에서 부모-자식 컴포넌트 관계는 props는 아래로, events 위로 라고 요약 할 수 있다. 부모는 props를 통해 자식에게 데이터를 전달하고 자식은 events를 통해 부모에게 메시지를 보낸다. ( parent => child: props || child => parent: emit )

HTML 속성은 대소 문자를 구분하지 않으므로 문자열이 아닌 템플릿을 사용할 때 camelCased prop 이름에 해당하는 kebab-case(하이픈 구분)를 사용해야 한다.


<div id="app">
<props-component props-data="props-data"></props-component>
</div>
<script>
new Vue({
el: '#app',
components: {
'props-component': {
props: ['props-data'],
template: '<div>{{ propsData }}</div>'
}
}
});
</script>


  • dynamic props
<div id="app">
<dynamic-props-component :dynamic-props-data="dynamicPropsData"></dynamic-props-component>
</div>
<script>
new Vue({
el: '#app',
data: {
dynamicPropsData: 'dynamic-props-data',
},
components: {
'dynamic-props-component': {
props: ['dynamic-props-data'],
template: '<span>{{ dynamicPropsData }}</span>'
}
}
});
</script>


  • props 주의점 ( 단방향 데이터 흐름 )

 컴포넌트 사이의 모든 props는 parent -> child 사이의 단방향 바인딩을 형성하위 컴포넌트가 부모의 상태를 변경하여 앱의 데이터 흐름을 추론하기 더 어렵게 만드는 것을 방지.


1. props의 초기 값을 컴포넌트 로컬 데이터 속성으로 정의

<div id="app">
<caution-initial :initial-counter="counter"></caution-initial></div>
</div>
<script>
var v2 = new Vue({
el: '#app',
data: {
counter: 0
},
components: {
'caution-initial': {
props: ['initial-counter'],
template: '<div><button @click="addCounter">{{ counter }}</div>',
data: function () {
return {
counter: this.initialCounter
};
},
methods: {
addCounter () {
this.counter++;
}
}
}
}
});
</script>


2. props 값으로 부터 계산된 속성을 정의

<div id="app">
<cuation-computed :props-data="propsData"></cuation-computed>
</div>
<script>
var v1 = new Vue({
el: '#app',
data: {
propsData: 'props-data'
},
components: {
'cuation-computed': {
props: ['props-data'],
template: '<div>{{ computedPropsData }}</div>',
computed: {
computedPropsData () {
return 'computed-' + this.propsData;
}
}
}
}
});
</script>


  • props 검증

props 검증을 통해 props 데이터 타입, 기본값, 유효성 검사를 강제. ( 객체 형식으로 props 속성에 대한 값에 정의. )

- type : String, Number, Boolean, Object, Array, Function, Symbol

- default : 기본값

- required : 필수값

- validator : 유효성 검사

props: {
'props 검증': {
type: String, Number, Boolean, Object, Array, Function, Symbol
type: [],
default: function () { // 기본값 정의
return 'default';
},
validator: function ( value ) { // 유효성 검사
return value > 0;
},
required: true // 필수값 설정
},
}


  • props가 아닌 존재하는 속성 교체/병합

기본적으로 부모 컴포넌트에 제공된 값은 자식 컴포넌트에서 설정되어 값을 대체. ( class와 style 속성은 병합됨 )

inheritAttrs 존재하는 속성 병합 ( Boolean )

<div id="app">
<bs-date-input type="date" data-3d-date-picker="true"></bs-date-input>
</div>
<script>
new Vue({
el: '#app',
components: {
'bs-date-input': {
inheritAttrs: true,
template: '<input class="form-control">'
}
}
});
</script>


'Vue' 카테고리의 다른 글

event bus  (0) 2019.02.08
사용자 정의 이벤트  (0) 2019.02.06
컴포넌트  (0) 2019.01.26
필터  (0) 2019.01.26
폼 입력 바인딩, 모델  (0) 2019.01.23