FE/Vue.js

[ Vue.js ] 프로젝트 구성

지니엠 2024. 5. 8. 16:29

 

 

 

 

 

 

 

 

프로젝트 생성 및 로그인 폼 UI 구성

 

 

- 새 프로젝트 생성 -

vue create vue3-form

Default ([Vue 3] babel, eslint) 선택

cd vue3-form

npm run serve

 

 

 

App.vue

기존 내용을 모두 지우고, vbc+tab 기본적인 템플릿 생성

간단한 로그인 화면을 만들거고

<template>
  <form action="" >
    <div>
      <label for="userId">ID: </label>
      <input id="userId" type="text"  />
    </div>
    <div>
      <label for="password">PW: </label>
      <input type="text" />
    </div>
    <button type="submit">로그인</button>
  </form>
</template>

이렇게 작성하면

기본적인 로그인UI가 출력된다(스타일은 생략)

이제 입력한 값을 데이터로 받아오게 만들자

<script> 태그안에 아래 코드 작성

  data() {
    return {
      username: "",
      password: "",
    };
  },

Reactivity가 반영된 데이터이고, 이제 위쪽 input과 연결을 해줘야하는데 그때 사용하는것이 v-model 이다!

 

 

<template> 태그안 내용 추가

<template>
  <form action="">
    <!-- v-on -->
    <div>
      <label for="userId">ID: </label>
      <input id="userId" type="text" v-model="username" />
    </div>
    <div>
      <label for="password">PW: </label>
      <input type="text" v-model="password" />
    </div>
    <button type="submit">로그인</button>
  </form>
</template>

v-model로 data값연결해줬고, 이제 화면을 출력하면

 

이렇게 바로바로 값이 나오는걸 확인할 수 있다.

 

 

 

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

 

form태그안에서 input에 입력이 되거나, 버튼을 눌렀을 때 폼에서는 submit이벤트로 동작을 할 수 있게된다.

이때 사용하는것이 @(v-on):submit 

<form action="" @:submit="submitForm">

submitForm 메서드를 생성하고

 methods: {
    submitForm() {
      console.log("제출됨");
    },
  },

이렇게 코드를 작성하면 원하는 값이 나오지 않고 새로고침만된다.

여기서 새로고침 되는것이 폼의 기본적인 동작이기 때문에, 이걸 막기위해서 event.preventDefault 라는걸 사용한다.

  methods: {
    submitForm(event) {
      event.preventDefault();
      console.log("제출됨");
    },
  },

수정해줬는데, 이렇게 사용하는것도 가능하지만(JavaScript를 제어할때 이벤트를 직접적으로 제어하는 방법)

Vue에서는 직접제어하는것이 아니라 템플릿 표현식에서 submit.prevent라고 하면

이벤트의 기본동작을 막겠다고 지정할 수 있다.(디렉티브의 이벤트 모디파이)

 

<template>
  <form action="" @:submit.prevent="submitForm">
    <!-- v-on -->
    <div>
      <label for="userId">ID: </label>
      <input id="userId" type="text" v-model="username" />
    </div>
    <div>
      <label for="password">PW: </label>
      <input type="text" v-model="password" />
    </div>
    <button type="submit">로그인</button>
  </form>
</template>

<script>
export default {
  data() {
    return {
      username: "",
      password: "",
    };
  },
  methods: {
    submitForm() {
     // event.preventDefault();
      console.log("제출됨");
    },
  },
};
</script>

 

제출되는것까지 확인이 되었다.

 

 

 

여기서 이 데이터들을 서버로 보내줘야하는데 이때 필요한것이 axios이다.

 

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

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

github.com

axios 라이브러리를 터미널에서 설치해준다

npm install axios

yarn add axios

 

설치가 완료되면 package.json에 

  "dependencies": {
    "axios": "^1.6.8",
    "core-js": "^3.8.3",
    "vue": "^3.2.13"
  },

이렇게 axios 가 추가된걸 확인할 수 있다.

 

라이브러리를 사용하려면 import를 해줘야한다 !

import axios from 'axios'

 

이제 어떤서버로 보낼거지 정해야하는데, 

 

https://jsonplaceholder.typicode.com/

 

JSONPlaceholder - Free Fake REST API

{JSON} Placeholder Free fake and reliable API for testing and prototyping. Powered by JSON Server + LowDB. Serving ~3 billion requests each month.

jsonplaceholder.typicode.com

일단 JSONPlaceholder라는 Fake API를 사용한다.

 

 

<script>
import axios from "axios";
export default {
  data() {
    return {
      username: "",
      password: "",
    };
  },
  methods: {
    submitForm() {
      // event.preventDefault();
      const data = {
        username: this.username,
        password: this.password,
      };
      axios
        .post("https://jsonplaceholder.typicode.com/users/", data)
        .then((Response) => {
          console.log(Response);
        });
      console.log("제출됨");
    },
  },
};
</script>

1. axios에 post해줄 URL을 연걸하고, then을 이용해서 응답을(response) 받는다.

2. console로 응답확인해주고,

3. 넘길 데이터를 그냥 풀어서 쓸수도 있지만 객체안에 username과 password를 넣어서 post해주는 방식으로 만들어준다.

4. this 는 '이 뷰의 데이터를 의미한다' 라는 뜻 

 

이제 서버가 연결되었는지 확인해보자

출력된 화면을 새로고침을 해주고, 개발자 도구에서 Network를 확인해보면 되는데, 

id, pw에 값을 입력하고 로그인 버튼을 누르면

이랬던 Network 창에 

users가 추가되는걸 확인할 수 있다.

위의 users를 클릭하면 

Headers에 방금 지정한 URL이 포스트 형태로 날라가고, 상태코드 201로 정상적으로 성공했다는 뜻이다.

Payload를 보면 방금 입력한 id와 pw값도 확인할 수 있다.

 

 

 

Vue Composition API 코드로 변환하기

지금까지 작성한 코드들을 composition API로 변환해보자

Setup()을 사용하는데, 

인스턴스 옵션 속성 API의 전체적인 개념을 잡고, Setup API를 사용하는것을 추천

Setup을 사용하면 재사용이라던지 코드의 간결화에서 유리하기때문에 사용하는것

 

import axios from "axios";
import { ref } from "vue";
export default {
  setup() {
    // data와 완전하게 동일하다.
    var username = ref("");
    var password = ref("");

    // methods
    var submitForm = () => {
      axios
        .post("https://jsonplaceholder.typicode.com/users/", {
          username: username.value,
          password: password.value,
        })
        .then((Response) => {
          console.log(Response);
        });
    };
    return { username, password, submitForm };
  },

 

1. 우선 setup으로 열고, data를 먼저 선언해야한다. 이때 ref를 사용하는데 vue패키지에서 가져오기때문에 자동으로 import된다.

2. ref에 빈문자를 선언하게 되면 리액티비티가 주입된 username과 password를 ref라는 형태로 나타낼 수 있는것

3. 그다음 메서드 생성. 함수표현식으로 작성할 수 있다.

4. 데이터를 보낼때 username에 .value를 붙인다 >> ref로 지정한 변수안에 value가 우리가 원하는 값이라는 뜻(컴포지션API의 특징)

5. setup이라는 속성에서 return으로 사용하고자하는 값들을 보내주면 이 인스턴스 옵션내에서 다 사용할 수 있게된다.

>> 리턴한 값들은 템플릿 표현식에서도 사용가능, 모든 메서드에서 다 접근가능