[javascript] Vue.js에서의 게시판 개발 방법

Vue.js는 사용하기 쉬운 JavaScript 프레임워크로, 웹 애플리케이션을 개발하는데 많은 도움을 줍니다. 이번 글에서는 Vue.js를 사용하여 간단한 게시판을 개발하는 방법에 대해 알아보겠습니다.

프로젝트 설정

먼저, Vue 프로젝트를 설정합니다. 다음 명령어를 사용하여 Vue CLI를 설치하고, 새로운 프로젝트를 생성합니다.

npm install -g @vue/cli
vue create bulletin-board

프로젝트 생성 후 다음과 같이 입력하여 필요한 의존성 패키지를 설치합니다.

cd bulletin-board
npm install axios vue-router vuex

컴포넌트 생성

게시판에는 여러 개의 컴포넌트가 필요합니다. 예를 들어, 게시글 목록 컴포넌트, 게시글 상세 보기 컴포넌트, 게시글 작성 컴포넌트 등이 있을 수 있습니다.

Vue CLI에서 제공하는 명령어를 사용하여 컴포넌트를 생성합니다.

vue generate BulletinList
vue generate BulletinDetail
vue generate BulletinCreate

각각의 컴포넌트는 BulletinList.vue, BulletinDetail.vue, BulletinCreate.vue와 같은 파일 이름으로 생성됩니다.

라우팅 설정

Vue 라우터를 사용하여 각 컴포넌트를 페이지에 매핑합니다. 프로젝트 루트에 있는 router/index.js 파일을 열고 다음과 같이 수정합니다.

import Vue from 'vue';
import VueRouter from 'vue-router';
import BulletinList from '@/views/BulletinList';
import BulletinDetail from '@/views/BulletinDetail';
import BulletinCreate from '@/views/BulletinCreate';

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    name: 'BulletinList',
    component: BulletinList,
  },
  {
    path: '/bulletin/:id',
    name: 'BulletinDetail',
    component: BulletinDetail,
  },
  {
    path: '/create',
    name: 'BulletinCreate',
    component: BulletinCreate,
  },
];

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
});

export default router;

위의 코드에서 path는 경로를 가리키며, component는 해당 경로로 이동할 때 표시될 컴포넌트를 가리킵니다.

데이터 관리

Vue.js에서 데이터를 관리하기 위해 Vuex를 사용합니다. 프로젝트 루트에 있는 store/index.js 파일을 열고 다음과 같이 수정합니다.

import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    bulletins: [],
  },
  mutations: {
    setBulletins(state, bulletins) {
      state.bulletins = bulletins;
    },
  },
  actions: {
    fetchBulletins({ commit }) {
      axios.get('/api/bulletins')
        .then((response) => {
          commit('setBulletins', response.data);
        });
    },
  },
});

위의 코드에서 state는 애플리케이션의 상태를 담고 있는 객체이며, mutationsstate를 변경하는 메서드를 정의합니다. actions는 비동기로 동작하는 작업을 수행하고, commit을 통해 mutations를 호출하여 상태를 변경합니다.

API 연결

Vue.js에서 서버로부터 게시글 데이터를 가져오기 위해 HTTP 요청을 보내야 합니다. 이를 위해 axios를 사용합니다.

import axios from 'axios';

export default {
  getBulletins() {
    return axios.get('/api/bulletins');
  },
  getBulletin(id) {
    return axios.get(`/api/bulletins/${id}`);
  },
  createBulletin(data) {
    return axios.post('/api/bulletins', data);
  },
};

위의 코드는 API와 통신하는 메서드를 포함하는 bulletinService 모듈입니다.

게시판 컴포넌트에서 API 사용

게시판의 목록 컴포넌트에서 Vuex의 actions를 호출하여 서버에서 데이터를 가져와 출력할 수 있습니다. 다음과 같이 BulletinList.vue 파일을 수정합니다.


<template>
  <div>
    <div v-for="bulletin in bulletins" :key="bulletin.id">
      <h3>{{ bulletin.title }}</h3>
      <p>{{ bulletin.content }}</p>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      bulletins: [],
    };
  },
  mounted() {
    this.$store.dispatch('fetchBulletins')
      .then((bulletins) => {
        this.bulletins = bulletins;
      });
  },
};
</script>

위의 코드에서 mounted 라이프사이클 훅에서 fetchBulletins 액션을 호출하여 게시글 데이터를 가져옵니다. 가져온 데이터는 bulletins 배열에 저장됩니다.

마치며

이제 Vue.js를 사용하여 간단한 게시판을 개발하는 방법에 대해 알아보았습니다. Vue.js의 간편한 문법과 다양한 기능을 활용하여 더 복잡하고 기능적인 게시판을 만들 수도 있습니다.

더 자세한 내용은 Vue 공식 문서를 참고하시기 바랍니다.