- 뷰 컴포넌트(component) 활용하기
<head>
<title>끝말잇기</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<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('wordRelay', { // 전역 컴포넌트
template: `
<div>
<div>{{word}}</div>
<form v-on:submit="onSubmitForm">
<input type="text" ref="answer" v-model="value">
<button type="submit">입력!</button>
</form>
<div>{{result}}</div>
</div>
</div>
`,
props: ['startWord'],
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 = '';
} else {
this.result = '땡';
this.value = '';
}
this.$ref.answer.focus();
}
}
})
</script>
<script>
const app = new Vue({
el: '#root'
});
</script>
</body>