본문 바로가기

프론트엔드/뷰(Vue)

Vue를 이용한 구구단 만들기 (v-on:submit, ref, v-model)

반응형
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>{{first}} 곱하기 {{second}}는?</div> <!--텍스트 노드이면 중괄호 두개로 가능하다{{안에는 자바스크립트를 그냥 넣어도 작동한다 예를 들어 first+second}}-->
        <form v-on:submit="onSubmitForm">
            <input type="number" v-model="value" ref="answer"> <!--인풋과 데이터를 서로 연결하겟다  v-model-->
            <button type="submit">입력</button>
        </form>
        <div id="result">{{result}}</div>
    </div>
    <script>
        const app = new Vue({
            el:'#root',
            data:{
                first : Math.ceil(Math.random() * 9), //첫번째 숫자
                second : Math.ceil(Math.random() * 9), //두번째 숫자
                value:'', // 입력하는곳
                result:'',//결과값
            },
            methods: {
            onSubmitForm(e) {
                e.preventDefault();
                //const userInput = parseInt(this.value); // Convert user input to a number
                console.log(this)
                if (this.first * this.second === parseInt(this.value)) {
                    this.result = '증답'; //정답을 맞춘다음
                    this.first = Math.ceil(Math.random() * 9); //다시 숫자를 랜덤하게 뽑아낸다
                    this.second = Math.ceil(Math.random() * 9); // 두번째 숫자도 마찬가지
                    this.value = ''; // value 값은 비워준다
                    this.$refs.answer.focus(); //$refs 는 선택하겠다 라는 뜻
                    this.$refs.answer.value = '123' // 이런식으로 값을 직접 넣어주면 안됌. 화면에서 입력받는 값과 불일치하는 현상이 남. 화면은 직접 건들지 x 
                } else {
                    this.result = '땡~';
                    this.value = ''; 
                }
            },
        },
        })
    </script>
</body>
</html>

v-on:submit

버튼을 클릭하거나 Enter키를 눌러 양식 제출을 하면 Vue의 구성요소에서 정의된 onSubmitForm가 실행된다.

동일한 결과를 얻기 위해서는 @submit.prevent="onSubmitForm"도 사용이 가능하다.

 

 

v-model

변경과 데이터를 엮어줌, v-model이라고 선언한 곳과 데이터가 쌍방향으로 연동된다.

(form의 input요소나 textarea, select 요소에 데이터 바인딩을 만들고 싶을때)

 

 

refs 

개발자가 직접 DOM 엘리먼트에 접근해야 하는 경우가 있을 수 있다.(ex. input에 커서를 올리지 않아도 focus 유지 되게끔)

ref = "answer" 로 선언해주고,  this.$refs.answer.focus() 이런식으로 스크립트에 넣어주면 된다.

 

 

e.preventDefault(); 

새로고침이 브라우저 기본동작인데 이걸 막아주는 역할을 한다.

(a 태그에 preventDefault하면 링크로 넘어가는 기본동작을 막아줌)

 

반응형
LIST