Vue 코드 이해해보기

김현중·2025년 1월 12일

연구소

목록 보기
7/34

Vue.js를 처음 공부하면서 작성한 코드에 대해 남겨봅니다.
여기서는 2개의 input과 1개의 button이 있는 로그인 폼을 개발했습니다.

1. Vue CLI Setting

vue create '프로젝트 폴더 위치'

* CLI는 Command Line Interface의 약자

먼저 vue create를 통해 프로젝트를 생성했을 때 설치되는 파일들에 대해 알아보겠습니다.
여기서는 Vue 3를 선택했습니다.

vue.config.js

vue.config.js는 Vue CLI 프로젝트의 설정 파일입니다.

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true
})
  • defineConfig : Vue CLI의 설정을 정의하는 헬퍼 함수로, TypeScript 사용 시 자동 완성 기능을 제공합니다. 추후 프로젝트에서는 TypeScript를 사용할 것이므로 유용한 기능이라 생각합니다.
  • transpileDependencies : node_modules 내의 디펜던시들을 Babel로 트랜스파일할지 여부를 설정합니다. 여기서는 true로 설정했습니다.

jsconfig.json

jsconfig.json은 JS 프로젝트의 루트 디렉토리에 위치하는 설정 파일로, IDE에서 JS 개발 경험을 향상시키는 역할을 합니다.

{
  "compilerOptions": {
    "target": "es5",	// ES5로 컴파일
    "module": "esnext",	// 최신 ES 모듈 시스템 사용
    "baseUrl": "./",	// 모듈 해석의 기준이 되는 기본 디렉토리 설정
    "moduleResolution": "node",	// 모듈 해석 방식을 Node 방식으로 설정
    "paths": {	// 경로 별칭
      "@/*": [
        "src/*"
      ]
    },
    "lib": [	// 사용 가능한 라이브러리 정의
      "esnext",	// 최신 JS 기능
      "dom",	// DOM API
      "dom.iterable",
      "scripthost"
    ]
  }
}

babel.config.js

babel.config.js는 Babel의 설정 파일로, JS 코드를 변환하는 규칙을 정의합니다.

module.exports = {
  presets: ["@vue/cli-plugin-babel/preset"],
};
  • @vue/cli-plugin-babel.preset : Vue CLI에서 제공하는 기본 Babel 프리셋으로, Vue 프로젝트에 필요한 기본적인 JS 변환 규칙들을 포함합니다.

.eslintrc.js

.eslintrc.js는 ESLint의 설정 파일로, 코드 품질과 스타일을 검사하는 규칙을 정의합니다.

module.exports = {
  root: true,	// 현재 디렉토리를 ESLint 설정의 루트로 지정
  parserOptions: {
    requireConfigFile: false,	// 바벨 설정 파일(babel.config.js) 필요 여부
    parser: "@babel/eslint-parser",	// JS 코드를 파싱할 파서 지정
    ecmaVersion: 2020,
    sourceType: "module",	// 모듈 시스템 사용
  },
  env: {
    es6: true,	// ES6 문법 활성화
    node: true,	// Node.js 전역 변수와 구문 활성화
  },
};

main code

main.js

main.js는 Vue 애플리케이션의 진입점입니다.

import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')
  • createApp : Vue 3에서 앱 인스턴스를 생성하는 함수
  • App : 루트 컴포넌트
  • mout('#app') : 앱을 DOM의 '#app' 요소에 마운트

여기에 각종 플러그인, 라이브러리, 스타일, 전역 속성 등을 import해서 프로젝트에 전반적으로 사용할 수 있습니다.


components

App.vue

App.vue는 Vue 애플리케이션의 루트 컴포넌트입니다. 여기서는 로그인 폼을 구현했습니다.

  1. 템플릿 구조 :
<template>
  <!-- .prevent는 기본 폼 제출 동작을 막습니다 -->
  <form v-on:submit.prevent="submitForm">
    <!-- 아이디 입력 필드 -->
    <div>
      <label for="username">id: </label>
      <input type="text" id="username" v-model="username" />
    </div>
    <!-- 비밀번호 입력 필드 -->
    <div>
      <label for="password">pw: </label>
      <input type="password" id="password" v-model="password" />
    </div>
    <button type="submit" v-on:click="submitForm">로그인</button>
  </form>
</template>
  • v-on:submit.prevent : 여기서 .prevent는 event.preventDefault()와 같은 동작을 합니다. 폼 제출 시 새로고침을 방지합니다.
  • submitForm : 서브밋 폼 메서드에서 폼 데이터를 처리합니다.
  • v-model : v-model 디렉티브를 사용하여 입력 필드와 데이터 속성을 연결합니다. 사용자의 입력이 자동으로 컴포넌트의 데이터에 반영됩니다.

  1. 스크립트 부분 :
<script>
import axios from "axios";

export default {
  // 컴포넌트의 데이터 정의
  data: function () {
    return {
      username: "", // 사용자 입력 아이디 저장
      password: "", // 사용자 입력 비밀번호 저장
    };
  },

  // 컴포넌트의 메서드 정의
  methods: {
    submitForm: function () {
      // 입력된 데이터 로깅
      console.log(this.username, this.password);
      // API 엔드포인트 URL
      var url = "https://jsonplaceholder.typicode.com/posts"; 
      // 전송할 데이터 객체
      var data = {
        username: this.username,
        password: this.password,
      };

      // axios를 사용한 POST 요청
      axios
        .post(url, data)
        .then((res) => {
          // 성공 시 응답 데이터 로깅
          console.log(res);
        })
        .catch((err) => {
          // 실패 시 에러 로깅
          console.log(err);
        });
    },
  },
};
</script>
  • axios를 사용해 서버에 POST 요청을 전송하고, Promise 기반의 비동기 처리를 진행했습니다.

  1. 전체 코드
<template>
  <form v-on:submit.prevent="submitForm">
    <div>
      <label for="username">id: </label>
      <input type="text" id="username" v-model="username" />
    </div>
    <div>
      <label for="password">pw: </label>
      <input type="password" id="password" v-model="password" />
    </div>
    <button type="submit" v-on:click="submitForm">로그인</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/posts";
      var data = {
        username: this.username,
        password: this.password,
      };
      axios
        .post(url, data)
        .then((res) => {
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
};
</script>

<style>
body {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

form {
  display: flex;
  flex-direction: column;
  align-items: center;
}

div {
  margin-bottom: 10px;
}

input {
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

button {
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}
</style>


Vue.js 입문 강의를 들으며 처음 .vue 파일의 코드를 작성해봤습니다.
평생 jsx기반의 코드만 작성하다가 새로운 스택에 입문하니 많은 어려움이 있네요. 그래도 프로젝트를 진행하면서 챗봇과의 꾸준한 소통을 하다보면, 언젠가 vue 코드도 익숙해지고, 원하는 코드를 작성할 수 있을거라 생각합니다. 뭐 그때까지 포기하지 않고 계속 공부해야죠

profile
진짜 성실한 사람

0개의 댓글