본문 바로가기

카테고리 없음

Vue를 이용한 끝말잇기 만들기

반응형
SMALL
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-compatible" content="ie=edge">
    <title>끝말잇기</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="root">
        <div>{{word}}</div> // 화면에 보여주고자 하는 단어
        <form v-on:submit="onSubmitForm"> //버튼 누르면 onSubmitForm 함수 실행
            <input type="text" v-model="value" ref="answer">  // 입력값 넣는곳 v-model로 데이터와 연결
            <button type="submit">입력</button>
            <div>{{result}}</div> // 결과값
        </form>
    </div>
    <script>
        const app = new Vue ({ //Vue한테 태그 통제권을 넘기겠다는 뜻
            el : '#root',
            data : {
                word : '안녕하세요',
                result : '',
                value : '',
            },
            methods:{
                onSubmitForm(e){
                    e.preventDefault();
                    if(this.word[this.word.length - 1] === this.value[0]){ // 마지막 단어가 value의 첫 단어와 같으면 true
                        this.result = '딩동댕'; 
                        this.word = this.value;
                        this.value = '';
                        this.$refs.answer.focus();
                    }else{
                        this.result = '땡';
                        this.value = '';
                        this.$refs.answer.focus();
                    }
                }
            },
        });
    </script>
</body>
</html>

<!--
1. 화면에 보여지고자 하는 걸 html로 마크업한다.
2. 브라우저를 보고 데이터가 지속적으로 바뀌는 부분을 체크해서 data에 변수를 선언해준다.
3. v-mode나 v-on:submit등을 선언해준다.
4. html에 data에 선언한 것들을 연결시켜준다.{{}} / 바뀌는 것에 주목!

5. word의 마지막글자와 value의 첫번째 글자가 똑같으면 딩동댕을 배출하고, value값을 다시 word로 변경해줌, 그리고 value는 리셋
6. else 일때는 땡 배출, value 초기화

7. 정리) 화면은 처음에 만들어 놓고 데이터를 중심으로 작성한다.
-->

 

반응형
LIST