30. [최종 프로젝트]사용자 입력 폼 만들기

freejia·2021년 10월 19일
0

야금야금 Vue.js

목록 보기
29/29

캡틴판교 장기효님의 Vue.js시작하기 인프런 강의를 수강하고 내용을 정리했다.
매일 20분 야금야금 Vue.js 고생했다.(2021년 9월 26일~ 10월19일) 이제 복습하자.

IDE: Visual Studio Code
크롬 뷰 개발자 도구: Vue.js devtools


[Vue.js 시작하기]기본강의의 마지막 파트다.
Vue CLI 로 프로젝트를 생성해서 '사용자 입력 폼'을 만들어보자.

프로젝트 생성 및 마크업 작업

1. Vue CLI로 프로젝트 생성

터미널을 하나 열어서 vue-form 이름의 프로젝트를 생성한다.

vue create vue-form


Defalut [vue 2]를 선택하자.

2. 프로젝트 디렉토리에서 뷰 실행

$ cd vue-form
$ npm run serve

뷰를 실행하고, 브라우저에서 개발자도구 뷰를 켜고 정상적으로 App 컴포넌트가 만들어지는지 확인하자.

3. App.vue 에 div 태그 하나만 만들고, HelloWorld컴포넌트 삭제

App.vue의 내용을 지우고, 아래처럼 새로 작성하자.

<template>
  <div>
    hi
  </div>
</template>

<script>
export default {

}
</script>

<style>

</style>

기본 생성된 /src/components/HelloWorld.vue 컴포넌트는 삭제하자.

4. App.vue에 로그인 Form 만들기 :id, pw input과 버튼

<template>
  <form action="">
    <div>
      <label for="username">id: </label>
      <input id="username" type="text">
    </div>
    <div>
      <label for="password">pw: </label>
      <input id="password" type="password">
    </div>
    <button>login</button>
  </form>
</template>
<script>
export default {

}
</script>

<style>

</style>

v-model 속성과 submit 이벤트 처리

1. 뷰 data 정의

App.vue에 데이터를 정의하여 input 박스에 입력된 값을 뷰 data로 받자.

<script>
export default {
  data: function(){
    return {
      username: '',
      password: ''
    }
  }

}
</script>

컴포넌트 간에 데이터참조가 겹치지 않게 data는 function() return{} 형태로 써야한다.

2. v-model로 input태그에 입력된 값을 뷰 data에 바인딩하자

input에 값을 입력하면 즉시 뷰 데이터에 바인딩 됨을 개발자도구에서 확인할 수 있다.

<template>
  <form action="">
    <div>
      <label for="username">id: </label>
      <input id="username" type="text" v-model="username">
    </div>
    <div>
      <label for="password">pw: </label>
      <input id="password" type="password" v-model="password">
    </div>
    <button>login</button>
  </form>
</template>

<script>
export default {
  data: function(){
    return {
      username: '',
      password: ''
    }
  }

}
</script>

3. 버튼과 form에 v-on:submit을 추가하여 메서드 실행

버튼 type을 submit으로 만들면 form을 제출 시킨다.
form이 제출(submit)되면 기본적으로 '새고로침'된다.

v-on:submit 속성을 form태그에 작성하여 제출 시 실행되는 메서드 명을 적어준다

  <form v-on:submit="submitForm">
    <div>id...</div>
    <div>pw ...</div>
    <button type="submit">login</button>
  </form>

4. submitForm 메서드

id, pw에 값을 넣고 버튼을 클릭해보자. 콘솔에 id, pw가 출력된다.

<script>
export default {
  data: function(){
    return {
      username: '',
      password: ''
    }
  },
  methods:{
    submitForm: function(){
      console.log(this.username, this.password);
    }
  }
}
</script>

5. form submit의 새로고침 막기

폼을 제출하고 다음 페이지로 넘어가는 특징이 있다.
event.preventDefault() 로 기본적인 새로고침을 방지하자.

  methods:{
    submitForm: function(event){
      event.preventDefault();
      console.log(this.username, this.password);
    }
  }

뷰 에서 제공하는 prevent

v-on디렉티브에 prevent를 덧붙이면 새로고침을 방지할 수 있다.

<form v-on:submit.prevent="submitForm">

이벤트 버블링과 이벤트 캡쳐 이해하기

이벤트가 전달되는것과 이벤트가 어느 방향으로 흐르는지 이해하자

axios를 이용한 데이터 전송 및 form 구현

서드파티 라이브러리를 터미널에서 설치

axios라는 모듈을 현재 프로젝트에 install 한다.

npm i axios

1. 라이브러리를 App.vue에 import

export default 위에 import 를 적어준다.

import axios from 'axios';

2. submitForm 메서드에 axios post() 작성

axios : 웹서버 간에 데이터를 주고받기 위한 HTTP 라이브러리

아래 URL은 RESTapi 에 따라 데이터를 보내고 결과를 받을 수 있다.

var url = 'https://jsonplaceholder.typicode.com/users';

post()에 url과 data를 넘긴다.

  methods:{
    submitForm: function(){
      var url = 'https://jsonplaceholder.typicode.com/users';
      var data = {
        username: this.username,
        password: this.password
      }
      axios.post(url, data);

      console.log(this.username, this.password);
    }
  }

3. axios.post()의 then()과 catch() 함수 작성

post가 성공했을 때의 응답을 then()함수 내에서 response 파라미터 출력으로 확인한다.
post가 실패했을 때 에러 내용을 catch() 함수 내에서 error 파라미터 출력으로 확인한다.

  methods:{
    submitForm: function(){
      console.log(this.username, this.password);

      var url = 'https://jsonplaceholder.typicode.com/users';
      var data = {
        username: this.username,
        password: this.password
      }
      axios.post(url, data)
      .then(function(response){
        console.log(response);
      })
      .catch(function(error){
        console.log(error);
      })
    }
  }

4. 개발자 도구에서 axios 전송 결과 확인

Console 에 data 객체 응답이 출력됨을 확인할 수 있다.

Network 탭에서는 Request, Response 내용을 확인할 수 있다.

Network탭의 Response 에서는 결과값 JSON 을 확인할 수 있다.


'사용자 입력 폼 만들기' 전체코드

<template>
  <form v-on:submit.prevent="submitForm">
    <div>
      <label for="username">id: </label>
      <input id="username" type="text" v-model="username">
    </div>
    <div>
      <label for="password">pw: </label>
      <input id="password" type="password" v-model="password">
    </div>
    <button type="submit">login</button>
  </form>
</template>

<script>
import axios from 'axios';

export default {
  data: function(){
    return {
      username: '',
      password: ''
    }
  },
  methods:{
    submitForm: function(){
      console.log(this.username, this.password);

      var url = 'https://jsonplaceholder.typicode.com/users';
      var data = {
        username: this.username,
        password: this.password
      }
      axios.post(url, data)
      .then(function(response){
        console.log(response);
      })
      .catch(function(error){
        console.log(error);
      })
    }
  }

}
</script>

<style>

</style>

배웠던 내용 정리

  • Reactivity
  • 인스턴스
  • 컴포넌트 : 화면을 구분하여 개발하는 개념
  • 컴포넌트 간에 통신 방법
    - props: 데이터를 내린다
    • event emit: 이벤트를 올린다
  • HTTP 통신 라이브러리 axios
  • 템플릿 문법
    -데이터 바인딩
    -뷰 디렉티브 v-
  • Vue CLI
  • 싱글 파일 컴포넌트 : webpack vue loader 공부하기

앞으로의 학습 순서

1. 공식 문서를 쭉 정독하는 것을 추천합니다.

자주 업데이트가 되는데 번역이 이것을 따라가기 힘들다.
원문을 보는 것을 권한다.

2. 스타일 가이드

코드 작성 스타일 정독을 추천합니다

3. Vue Cookbook

실제 구현 할 때 부딪힐 법한 실용적인 문법이나 고민들이 글로 정리되어 있다.

4. Vuex 공식문서

공식문서를 읽으면서 구현까지 해보시면 머리에 많이 남으실 것입니다.


다음 중급 강의도 화이팅 😊

profile
코딩 리딩 라이딩💛

0개의 댓글