728x90

Vue.js에서 회원가입 폼을 만들어 실습하면서 form을 통해 데이터를 전송하는 법을 알아보자

 

<template>
    <form action="" @submit.prevent="submitForm">
        <div>
            <label for="userId">아이디</label>
            <input id="userId" type="text" v-model="username">
        </div>
        <div>
            <label for="password">패스워드</label>
            <input id="password" type="password" v-model="password"> 
        </div>
        <button type="submit">회원가입</button>
    </form>
</template>

form을 만들고 input:text, label로 아이디와 패스워드를 입력 받을 폼을 만든다. 

 

submit 버튼은 디폴트로 submit 이벤트가 발생하고 페이지가 새로고침되기 때문에 새로고침을 막아야한다. 

 

새로고침을 막기 위해서 @submit 이벤트 핸들러에 .prevent를 붙여 preventDefault를 한다. 

그리고 submit 이벤트가 발생하면 폼의 input을 전송할 함수인 submitForm을 등록한다. 

 

            <input id="userId" type="text" v-model="username">

 input 태그에 v-model이라는 속성이 붙어있다. 

v-model은 input 태그의 value를 바인딩 해주는 디렉티브이다. 

만약 v-model을 사용하지 않는다면

input 태그에 input 이벤트가 발생할 때 input 태그의 value값을 가져와 v-bind: 바인딩해주는 작업을 해야한다. 

<input
  :username="text"
  @input="event => text = event.target.value">

 

data(){
	return {
    	username: '',
        password: '',
    }
}

 

그리고 data에 username과 password를 정의해준다. 

 

다음으로 비밀번호를 표시할지 password 타입으로 **처리할지 선택할 수 있는 체크박스를 만들어보자 

 <input type="checkbox" id="show" v-model="checked" @change="showPassword"> 
 
 data(){
 	return {
    	username: '',
        password: '',
        checked: '',
    }
 }
 methods:{
            showPassword(){
                if(this.checked){
                    document.querySelector('#password').type='text';
                }else{
                    document.querySelector('#password').type = 'password';
                }
            }
        }

template의 password input 태그 아래 checkbox를 추가하고 

change이벤트 핸들러에 showPassword 함수를 등록한다. 

showPassword 함수는 v-model로 받은 checked의 값에 따라 #password 태그의 type을 text와 password로 바꿔준다. 

여기서 this.checked는 data의 checked를 의미한다. 

체크박스가 해제 되었을 땐 password 타입

checked 상태에선 text 타입인 것을 확인할 수 있다. 

 

다중 checkbox, radio, select 를 사용한 input 태그를 작성

<template>
    <form action="" @submit.prevent="submitForm">
        <div>
            <label for="userId">아이디</label>
            <input id="userId" type="text" v-model="username">
        </div>
        <div>
            <label for="password">패스워드</label>
            <input id="password" type="password" v-model="password">
            <input type="checkbox" id="show" v-model="checked" @change="showPassword"> 
        </div>
        <div>
            <h3>성별</h3>
            <input type="radio" name="gender" id="M" value="남자" v-model="picked">
            <label for="M">M</label>
            <input type="radio" name="gender" id="F" value="여자" v-model="picked">
            <label for="F">M</label>
        </div>
        <div>
            <h3>기술스택</h3>
            <input type="checkbox" id="springboot" value="springboot" v-model="checkedNames">
            <label for="springboot">SpringBoot</label>
            <input type="checkbox" id="jpa" value="jpa" v-model="checkedNames">
            <label for="jpa">JPA</label>
            <input type="checkbox" id="mybatis" value="mybatis" v-model="checkedNames">
            <label for="mybatis">MyBatis</label>
            <input type="checkbox" id="vue" value="vue" v-model="checkedNames">
            <label for="vue">Vue</label>
            <input type="checkbox" id="react" value="react" v-model="checkedNames">
            <label for="react">React</label>
        </div>
        <div>
            <h3>주소</h3>
            <select name="address" id="address" v-model="selected">
                <option disabled value="">선택</option>
                <option value="서초구">서초구</option>
                <option value="관악구">관악구</option>
            </select>
        </div><br>
        <button type="submit">회원가입</button>
    </form>
</template>

 

input data를 전송하기 위한 submitForm 함수 작성 

 submitForm(){
                axios.post('https://jsonplaceholder.typicode.com/users/',{
                    username:this.username,
                    password:this.password,
                    checked:this.checked,
                    checkedNames:this.checkedNames,
                    picked:this.picked,
                    selected:this.selected
                }).then(response=>{
                    console.log(response);
                });
            },

 

axios는 비동기 요청방식 api이다. 

데이터를 서버로 전송하고 응답을 받아 처리할 수 있다. 

 

axios를 사용하기 위해 axios를 다운로드

https://github.com/axios/axios

 

GitHub - axios/axios: Promise based HTTP client for the browser and node.js

Promise based HTTP client for the browser and node.js - GitHub - axios/axios: Promise based HTTP client for the browser and node.js

github.com

 

사이트의 installing package manager에서 본인이 사용하는 패키지 매니저에 따라 명령어를 카피하고

프로젝트 디렉터리의 터미널에서 명령어를 실행한다. 

 

정상적으로 다운로드되면 package.json의 dependencies에 axios가 추가된다. 

import axios from 'axios'

App.vue에서 axios를 사용하기 위해 import 해준다. 

 

axios.post('url','data')으로 post 요청을 한다. 

 

이때 가상 서버 역할을 해줄 api가 필요하다면 

https://jsonplaceholder.typicode.com/users/를 이용할 수 있다. 

 

 data() {
            return {
                username: '',
                password: '',
                checked: '',
                checkedNames: [],
                picked: '',
                selected: ''
            }
        },
        
        
        
 axios.post('https://jsonplaceholder.typicode.com/users/',{
                    username:this.username,
                    password:this.password,
                    checked:this.checked,
                    checkedNames:this.checkedNames,
                    picked:this.picked,
                    selected:this.selected
                }).then(response=>{
                    console.log(response);
                });

 

 

data는 {객체형식으로 넘겨주면 된다.}

다중 checkbox는 배열로 넘겨주었다. 

input태그에 값을 입력하고 회원가입을 클릭하면 

users/ 요청이 날아가고 

payload를 클릭하면 요청할 때 보낸 data를 확인할 수 있다. 

 

.then은 서버로부터 응답을 받은 후의 로직을 작성할 수 있다. 

console.log(response) 에 의해 

response가 console창에 찍혔다. 

 

https://ko.vuejs.org/guide/essentials/forms.html

 

Form 입력 바인딩 | Vue.js

 

ko.vuejs.org

 

'Vue.js' 카테고리의 다른 글

Vue.js 프로젝트 생성하기  (0) 2023.11.29
Vue.js 기초 문법  (2) 2023.11.28
Vue.js Intro  (0) 2023.11.28

+ Recent posts