엘리먼트를 재사용 가능한 코드로서 캡슐화 하기 위한 개념.
Vue.component('simple-counter', {
template: '<button v-on:click="counter += 1">{{ counter }}</button>',
// 데이터는 기술적으로 함수이므로 Vue는 따지지 않지만
// 각 컴포넌트 인스턴스에 대해 같은 객체 참조를 반환합니다.
data: function () {
return data
}
})
<script type="text/x-template" id="plan-template">
<div>{{message}}</div>
</script>
Vue.component(‘plan’, {
template: "#plan-teamplate",
props: {message: String} // 이렇게 해주면 type도 잡아줌, 추가적으로 required 등의 설정도 가능
})
//실제 사용
<plan message="Test">”plan>
위의 방식은 전역으로 Compenent를 선언하는 방식, 다른 곳에서 접근이 안되도록 지역 선언하는 방식도 있음. 지역 선언 방식, 해당 부모 component에서만 사용할 수 있음.
let NewComponent = {
template: '<div>hi</div>'
}
Vue.component('another-comp', {
template: <div><new-component></div>,
components : {
'new-component': NewComponent
}
}
컴포넌트의 모듈화, 이를 통한 지역 선언
위와 같은 방식이 아닌, 컴포넌트를 따로 vue 파일로 정의하고, 해당 모듈을 불러와 지역 선언을 하여 사용할 수 있다. 이 방식을 통해서 컴포넌트를 모듈화하여 관리할 수 있다. 내부에서 import, required를 이용해 import, components 에 등록한다.
부모 → 자식: 자식 component에 props를 내려주고, 해당 props를 자식에서 받아 뿌려줌
자식 → 부모: custom method를 이용하여 변경 사항을 부모에게 noti한다.
this.$emit('noti할 event명',’payload)
를 사용하여 부모 메서드에게 event 전달
Props에 관하여