프론트엔드 노트에서는 간단한 Vue.js로 실시간 댓글 시스템을 만드는 미니 프로젝트를 소개하겠습니다. 이 프로젝트를 통해 Vue.js의 기본 개념을 이해하고, 실시간 데이터 처리를 위한 웹소켓(WebSocket) 사용 방법을 익힐 수 있습니다. 자, 이제 시작해 볼까요?

프로젝트 준비

먼저, Vue.js 프로젝트를 생성해야 합니다. Vue CLI를 사용하여 새 프로젝트를 만들어보겠습니다. 다음 명령어를 터미널에 입력하세요:

vue create real-time-comment

프로젝트 생성이 완료되면, 생성된 디렉토리로 이동합니다:

cd real-time-comment

기본 구조 설정

src 폴더 안에 components 폴더를 생성하고 그 안에 CommentBox.vue 파일을 만들어 댓글 입력과 표시를 위한 컴포넌트를 작성합니다.
<template>
  <div>
    <h1>실시간 댓글 시스템</h1>
    <input v-model="newComment" @keyup.enter="postComment" placeholder="댓글을 입력하세요" />
    <div class="comments">
      <div v-for="(comment, index) in comments" :key="index">{{ comment }}</div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      newComment: '',
      comments: []
    };
  },
  methods: {
    postComment() {
      if (this.newComment.trim()) {
        this.comments.push(this.newComment);
        this.newComment = '';
        // 웹소켓을 통해서 서버에 댓글을 전송하는 부분은 이곳에 추가합니다.
      }
    }
  }
}
</script>

<style scoped>
.comments {
  margin-top: 20px;
  border: 1px solid #ccc;
  padding: 10px;
}
</style>

웹소켓 설정

실시간 댓글 시스템을 만들기 위해 웹소켓을 사용합니다. 웹소켓 서버를 구축하기 위해 Node.js와 Express를 사용하여 간단한 웹소켓 서버를 만들어보겠습니다. 먼저, 새로운 디렉토리를 생성하고 server.js 파일을 만듭니다.

mkdir server
cd server
npm init -y
npm install express ws

이제 server.js 파일을 다음과 같이 작성합니다:

const express = require('express');
const WebSocket = require('ws');

const app = express();
const server = app.listen(3000, () => console.log('서버가 3000번 포트에서 실행 중입니다.'));
const wss = new WebSocket.Server({ server });

wss.on('connection', (ws) => {
  ws.on('message', (message) => {
    // 모든 클라이언트에게 메시지를 전송
    wss.clients.forEach(client => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(message);
      }
    });
  });
});

서버를 실행하기 위해 터미널에서 다음 명령어를 입력합니다:

node server.js

Vue.js 클라이언트와 웹소켓 연결

이제 Vue.js 클라이언트에서 웹소켓에 연결해보겠습니다. CommentBox.vue 파일을 다음과 같이 수정합니다:

export default {
  data() {
    return {
      newComment: '',
      comments: [],
      ws: null
    };
  },
  created() {
    this.ws = new WebSocket('ws://localhost:3000');
    this.ws.onmessage = (event) => {
      this.comments.push(event.data);
    };
  },
  methods: {
    postComment() {
      if (this.newComment.trim()) {
        this.ws.send(this.newComment);
        this.newComment = '';
      }
    }
  }
}

앱 실행

이제 모든 설정이 완료되었습니다. Vue 애플리케이션을 실행하기 위해 아래 명령어를 터미널에 입력합니다:

npm run serve

웹 브라우저를 열고 http://localhost:8080에 접속하면 실시간 댓글 시스템을 확인할 수 있습니다. 댓글을 입력하고 Enter 키를 누르면, 다른 클라이언트에서도 실시간으로 댓글이 표시됩니다.

마무리

이번 포스트에서는 Vue.js와 웹소켓을 이용하여 간단한 실시간 댓글 시스템을 구현해보았습니다. 이를 통해 Vue.js의 컴포넌트 구조와 웹소켓을 사용하는 방법에 대해 배울 수 있었습니다. 이 프로젝트를 확장하여 사용자 인증, 댓글 삭제 기능 등 다양한 기능을 추가해보는 것도 좋은 학습 방법입니다. 앞으로도 더 많은 프론트엔드 관련 내용을 다루겠습니다. 감사합니다!