ksundev 님의 블로그

[Vue] 폼 이벤트 제어 및 서버로 데이터 전송 본문

[개발] Vue.js/기본

[Vue] 폼 이벤트 제어 및 서버로 데이터 전송

ksundev 2025. 6. 29. 16:05

Vue.js 폼 이벤트 제어 및 서버로 데이터 전송

Vue.js에서 폼을 다루고 서버로 데이터를 전송하는 방법에 대해 알아보겠습니다. 폼 제출 시 페이지 새로고침을 방지하고, axios를 사용하여 서버와 통신하는 방법을 살펴보겠습니다.

폼 이벤트 제어

.prevent 수식어로 새로고침 방지

Vue.js에서 폼을 제출할 때 기본적으로 페이지가 새로고침됩니다. 이를 방지하기 위해 .prevent 수식어를 사용합니다.

<template>
  <form action="" @submit.prevent="submitForm">
    <div>
      <label for="userId">아이디:</label>
      <input id="userId" type="text" v-model="userId">
    </div>
    <div>
      <label for="password">비밀번호:</label>
      <input id="password" type="text" v-model="password">
    </div>
    <button type="submit">로그인</button>
  </form>
</template>

.prevent의 동작 원리

  • @submit.preventevent.preventDefault()와 동일한 기능을 수행합니다
  • 폼 제출 시 페이지 새로고침을 방지하고 Vue.js의 메서드만 실행됩니다
  • 사용자 경험을 향상시키고 SPA(Single Page Application)의 특성을 유지할 수 있습니다

Axios를 사용한 HTTP 통신

Axios 설치 및 import

npm install axios
import axios from 'axios'

export default {
  data() {
    return {
      userId: '',
      password: ''
    }
  },
  methods: {
    submitForm() {
      const data = {
        userId: this.userId,
        password: this.password
      }
      axios.post('https://jsonplaceholder.typicode.com/users', data)
      .then(response => {
        console.log(response)
      })
    }
  }
}

Axios의 장점

  1. Promise 기반: .then(), .catch()를 사용한 비동기 처리
  2. 자동 JSON 변환: 요청/응답 데이터를 자동으로 JSON으로 변환
  3. 요청/응답 인터셉터: 전역적으로 요청/응답을 가로채서 처리 가능
  4. 브라우저 호환성: 모든 주요 브라우저에서 지원

JSONPlaceholder란?

JSONPlaceholder 소개

JSONPlaceholder는 무료로 사용할 수 있는 가짜 REST API입니다. 프론트엔드 개발 시 백엔드 API가 준비되지 않았을 때 테스트용으로 사용할 수 있습니다.

주요 특징

  • 무료: 별도 가입 없이 즉시 사용 가능
  • RESTful API: 표준 HTTP 메서드(GET, POST, PUT, DELETE) 지원
  • 다양한 리소스: users, posts, comments, albums, photos, todos 제공
  • 실제 응답: 실제 서버와 유사한 응답 구조

테스트 방법

1. GET 요청 테스트

// 모든 사용자 조회
axios.get('https://jsonplaceholder.typicode.com/users')
  .then(response => {
    console.log(response.data)
  })

// 특정 사용자 조회
axios.get('https://jsonplaceholder.typicode.com/users/1')
  .then(response => {
    console.log(response.data)
  })

2. POST 요청 테스트

// 새 사용자 생성
const newUser = {
  name: '홍길동',
  email: 'hong@example.com',
  phone: '010-1234-5678'
}

axios.post('https://jsonplaceholder.typicode.com/users', newUser)
  .then(response => {
    console.log('생성된 사용자:', response.data)
  })

3. PUT 요청 테스트

// 사용자 정보 수정
const updatedUser = {
  id: 1,
  name: '김철수',
  email: 'kim@example.com'
}

axios.put('https://jsonplaceholder.typicode.com/users/1', updatedUser)
  .then(response => {
    console.log('수정된 사용자:', response.data)
  })

4. DELETE 요청 테스트

// 사용자 삭제
axios.delete('https://jsonplaceholder.typicode.com/users/1')
  .then(response => {
    console.log('삭제 완료:', response.status)
  })

브라우저에서 직접 테스트

브라우저 주소창에 다음 URL을 입력하여 직접 테스트할 수 있습니다:

  • https://jsonplaceholder.typicode.com/users - 모든 사용자
  • https://jsonplaceholder.typicode.com/users/1 - ID가 1인 사용자
  • https://jsonplaceholder.typicode.com/posts - 모든 게시물
  • https://jsonplaceholder.typicode.com/comments - 모든 댓글

Options API vs Composition API

현재 사용 중인 Options API

위 예제는 Options API 방식으로 작성되었습니다. Options API는 Vue 2에서부터 사용되던 전통적인 방식으로, 컴포넌트의 구조를 data, methods, computed, watch 등의 옵션으로 분리합니다.

export default {
  data() {
    return {
      userId: '',
      password: ''
    }
  },
  methods: {
    submitForm() {
      // 폼 제출 로직
    }
  }
}

Options API의 특징

  • 구조화된 코드: 각 기능별로 명확하게 분리
  • 학습 곡선: Vue.js를 처음 배우는 사람에게 친숙
  • 명확한 스코프: this를 통해 데이터와 메서드에 접근

다음 포스트 예고

다음 포스트에서는 Composition API를 사용하여 동일한 기능을 구현하는 방법을 살펴보겠습니다. Composition API는 Vue 3에서 도입된 새로운 방식으로, 더 유연하고 재사용 가능한 코드를 작성할 수 있게 해줍니다.

Composition API 미리보기

import { ref } from 'vue'
import axios from 'axios'

export default {
  setup() {
    const userId = ref('')
    const password = ref('')

    const submitForm = () => {
      const data = {
        userId: userId.value,
        password: password.value
      }
      axios.post('https://jsonplaceholder.typicode.com/users', data)
        .then(response => {
          console.log(response)
        })
    }

    return {
      userId,
      password,
      submitForm
    }
  }
}

실무 적용 팁

  1. 에러 처리: axios 요청에 .catch()를 추가하여 에러를 처리하세요
  2. 로딩 상태: 요청 중임을 사용자에게 알리는 로딩 상태를 추가하세요
  3. 환경 변수: API URL을 환경 변수로 관리하여 개발/운영 환경을 분리하세요
  4. 인터셉터: axios 인터셉터를 사용하여 공통 로직(인증 토큰, 에러 처리)을 처리하세요

결론

Vue.js에서 폼을 다루고 서버와 통신하는 기본적인 방법을 살펴보았습니다. .prevent 수식어로 페이지 새로고침을 방지하고, axios를 사용하여 JSONPlaceholder와 같은 테스트 API와 통신할 수 있습니다.

이번 포스트에서는 Options API 방식을 사용했지만, 다음 포스트에서 Composition API를 사용한 더 현대적인 방법을 다루겠습니다.


참고 자료: