Vue.js 를 배워보자

Vue.js를 이용한 사용자 로그인 구현: 단계별 가이드 및 심층 분석

_Blue_Sky_ 2024. 12. 18. 20:30
728x90

 

Vue.js를 이용하여 사용자 로그인 기능을 구현하는 것은 웹 애플리케이션 개발에서 필수적인 과정입니다. 이 글에서는 Vue.js를 활용하여 안전하고 효율적인 사용자 로그인 시스템을 구축하는 방법을 단계별로 자세히 설명하고, 각 단계에서 고려해야 할 사항과 추가적인 기능 구현 방법을 함께 다룹니다.


1. 프로젝트 생성 및 환경 설정



Vue CLI로 프로젝트 생성

vue create vue-login
cd vue-login
npm install axios vue-router
  • axios: API 호출을 위한 HTTP 클라이언트
  • vue-router: 라우팅 설정을 위한 패키지

 

728x90

 

프로젝트 디렉토리 구조

 

src/
├── components/
│   ├── Login.vue
│   ├── Home.vue
│   └── Dashboard.vue
├── router/
│   └── index.js
├── store/
│   └── index.js
├── App.vue
└── main.js

2. API 백엔드 준비

백엔드는 JWT(JSON Web Token)를 사용하는 인증 시스템이라고 가정하겠습니다. 로그인 시 POST /auth/login 엔드포인트를 호출하여 토큰을 받아옵니다.


3. Vue Router 설정

src/router/index.js

import { createRouter, createWebHistory } from 'vue-router';
import Login from '../components/Login.vue';
import Home from '../components/Home.vue';
import Dashboard from '../components/Dashboard.vue';

const routes = [
  { path: '/', component: Home },
  { path: '/login', component: Login },
  { 
    path: '/dashboard', 
    component: Dashboard,
    meta: { requiresAuth: true } // 인증이 필요한 라우트
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 인증 상태 확인 로직
router.beforeEach((to, from, next) => {
  const isAuthenticated = !!localStorage.getItem('token');
  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/login');
  } else {
    next();
  }
});

export default router;

 


4. Vuex (혹은 Pinia)로 상태 관리

src/store/index.js

import { createStore } from 'vuex';
import axios from 'axios';

const store = createStore({
  state: {
    token: localStorage.getItem('token') || '',
    user: null,
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token;
    },
    SET_USER(state, user) {
      state.user = user;
    },
  },
  actions: {
    async login({ commit }, credentials) {
      try {
        const response = await axios.post('https://api.example.com/auth/login', credentials);
        const token = response.data.token;
        localStorage.setItem('token', token);
        commit('SET_TOKEN', token);
        return true;
      } catch (error) {
        console.error('Login failed:', error);
        return false;
      }
    },
    logout({ commit }) {
      localStorage.removeItem('token');
      commit('SET_TOKEN', '');
      commit('SET_USER', null);
    },
  },
});

export default store;

5. 로그인 컴포넌트 구현

src/components/Login.vue

<template>
  <div class="login">
    <h1>Login</h1>
    <form @submit.prevent="handleLogin">
      <div>
        <label for="email">Email</label>
        <input v-model="email" type="email" id="email" required />
      </div>
      <div>
        <label for="password">Password</label>
        <input v-model="password" type="password" id="password" required />
      </div>
      <button type="submit">Login</button>
    </form>
    <p v-if="error">{{ error }}</p>
  </div>
</template>

<script>
import { mapActions } from 'vuex';

export default {
  data() {
    return {
      email: '',
      password: '',
      error: null,
    };
  },
  methods: {
    ...mapActions(['login']),
    async handleLogin() {
      const success = await this.login({ email: this.email, password: this.password });
      if (success) {
        this.$router.push('/dashboard');
      } else {
        this.error = 'Invalid email or password.';
      }
    },
  },
};
</script>

<style scoped>
/* 스타일 추가 */
</style>

728x90

 

6. 대시보드 및 로그아웃 기능

src/components/Dashboard.vue

<template>
  <div class="dashboard">
    <h1>Dashboard</h1>
    <button @click="handleLogout">Logout</button>
  </div>
</template>

<script>
import { mapActions } from 'vuex';

export default {
  methods: {
    ...mapActions(['logout']),
    handleLogout() {
      this.logout();
      this.$router.push('/login');
    },
  },
};
</script>

7. 메인 파일 설정

src/main.js

import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';

createApp(App).use(router).use(store).mount('#app');

8. 테스트 및 배포

  1. 개발 모드로 실행:
    npm run serve
    
  2. 브라우저에서 로그인 및 라우팅을 테스트합니다.

이와 같은 방식으로 Vue.js를 사용하여 사용자 로그인을 구현할 수 있습니다. 필요 시 추가적으로 사용자 권한에 따라 UI를 변경하거나, 인증이 필요한 API 호출 시 토큰을 포함하는 설정 등을 추가적으로 구현할 수 있습니다.

728x90