[Vue] 로그인 과정 정리

Yeong·2024년 7월 11일
0

1년 전에 팀프로젝트로 했던 JavaScript 기반의 'ZeroWave'프로젝트를 vue로 리팩토링을 혼자서 해보고 있다.

백엔드없이 프론트단에서 구현을 해보고 있는데, 우선 하드코딩의 방식으로 간단하게 하고있다.

1. 컴포넌트단에서 id랑 pw를 onChange 이벤트를 통하여 전달받는다.

<template>
  <main>
    <div :class="$style.Section1">
      <h1 style="color: #0475FF">Login</h1>
      <form :class="$style.loginBox" @submit.prevent="isLogin">
        <input type="text" placeholder="아이디" @change="isChangeUser($event, 'id')" />
        <input type="password" placeholder="비밀번호" @change="isChangeUser($event, 'pw')" />
        <span>
          <input type="checkbox" /> <label>로그인 상태 유지</label>
        </span>
        <button type="submit">로그인</button>
      </form>
    </div>
  </main>
</template>

<script>
import {mapMutations, mapState} from "vuex";

export default {
  data() {
    return {
      user: {
        id: '',
        pw: '',
      }
    }
  },
  computed: {
    ...mapState('auth', ['userId', 'userPw'])
  },
  methods: {
    ...mapMutations('auth', ['SET_USER']),
    async isLogin() {
      if (!this.user.id || !this.user.pw) {
        alert('아이디 또는 비밀번호를 입력해주세요.');
        return;
      }
      if (this.user.id !== 'yeong') {
        alert('해당 아이디가 존재하지않습니다.');
        return;
      }
      if (this.user.pw !== '123qwe') {
        alert('비밀번호가 올바르지않습니다.');
        return;
      }
      alert('로그인이 완료되었습니다.');
      await this.SET_USER(this.user);
      await this.$router.push('/home')
      this.resetUser();
    },
    async resetUser() {
      this.userId = '';
      this.userPw = '';
    },
    isChangeUser(e, field) {
      this.user[field] = e.target.value;
    }
  }
}

</script>

isChangeUser를 통해 컴포넌트 내 데이터에 저장하고, 로그인 버튼을 누르면 mutation을 통해 전역에서 state 값을 저장한다.(저장된 this.user을 보내기)

2. 전달받은 값은 스토어에서 관리

const authStore = {
    namespaced: true,
    state: {
        userId: localStorage.getItem('userId') || '',
        userPw: localStorage.getItem('userPw') || '',
    },
    getters: {
        isLogin(state) {
            return state.userId !== '';
        }
    },
    mutations: {
        SET_USER(state, user) {
            state.userId = user.id;
            state.userPw = user.pw;
            localStorage.setItem('userId', user.id);
            localStorage.setItem('userPw', user.pw);
        }
    }
}

export default authStore;

userId와 userPw가 있고, 로컬스토리지에 해당값이 없으면 빈값이다.
그리고 mutation을 통해서 받은 user의 id와 pw를 전달받는다.
(로컬스토리지에서도 저장!!)

3.해당값이 저장되면 getters 에서 로그인 상태 감지

로그인이 되어있느냐 아니느냐에 따라서 분기처리를 해줄 것이기때문에 getters를 사용하였다.

0개의 댓글

관련 채용 정보