Vue.js Component
2019-11-17
component
Vue에서 컴포넌트는 미리 정의된 옵션을 가진 Vue 인스턴스다.
컴포넌트는 기본 HTML 엘리먼트를 확장하여 재사용 가능한 코드를 캡슐화하는 데 도움을 준다.
예제: 끝말잇기
<div id="root">
<word-relay start-word = "가나다"></word-relay>
<word-relay start-word = "메모장"></word-relay>
<word-relay start-word = "기타"></word-relay>
</div>
<script>
Vue.component('word-relay',{ //글로벌 컴포넌트
template:`
<div>
<div></div>
<form v-on:submit="onSubmitForm">
<input type="text" ref="answer" v-model = "value">
<button type="submit"> 입력 </button>
</form>
<div></div>
</div>
`,
props: ['start-word'],
data(){
return {
word: this.startWord,
result: '',
value: '',
}
},
methods:{
onSubmitForm(e){
e.preventDefault();
if(this.word[this.word.length -1] === this.value[0]) {
this.result = '정답';
this.word = this.value;
this.value = '';
this.$refs.answer.focus();
}
else{
this.result = '오답';
this.value = '';
this.$refs.answer.focus();
}
},
},
})
</script>
<script>
const app = new Vue({
el: '#root',
});
</script>
컴포넌트의 템플릿은 하나의 부모 tag(<div>)로 묶어줘야 하고, data(){} 는 반드시 함수여야 한다.
컴포넌트 간 의사소통 방법으로 props를 사용한다.
부모 컴포넌트와 자식 컴포넌트는 서로 의사소통이 가능해야 하나 부모와 자식이 명확하게 정의된 인터페이스를 통해 가능한한 분리된 상태로 유지하는 것이 매우 중요하다.
부모는 props를 통해 자식에게 데이터를 전달하고 자식은 events를 통해 부모에게 메시지를 보낸다.