컴포넌트 만들기

1
2
3
4
5
6
7
8
9
10
11
12
<script type="text/javascript">
Vue.component('hello-component', {
template : '<div>hello world!!!</div>'
})
</script>
<body>
<div id="app">
<hello-component></hello-component>
<hello-component></hello-component>
<hello-component></hello-component>
</div>
</body>

props : 부모 > 자식 에게 데이터 전달

  • 기본 사용
1
2
3
4
5
6
7
8
// 컴포넌트를 아래와 같이 만들고.
Vue.component('child', {
props: ['message'],
template: '<span>{{ message }}</span>'
})

// 이렇게 사용하면, 컴포넌트의 props 로 message 값이 전달되어 진다.
<child message="hello!"></child>
  • 디폴트 값 + 데이터 검증

아래처럼 props를 선언하면, 데이터 타입 및 validation check가 가능하다.

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
32
Vue.component('example', {
props: {
// basic type check (`null` means accept any type)
propA: Number,
// multiple possible types
propB: [String, Number],
// a required string
propC: {
type: String,
required: true
},
// a number with default value
propD: {
type: Number,
default: 100
},
// object/array defaults should be returned from a
// factory function
propE: {
type: Object,
default: function () {
return { message: 'hello' }
}
},
// custom validator function
propF: {
validator: function (value) {
return value > 10
}
}
}
})

Reference