프로그래밍/Vue

vue3 setup / reactive를 이용한 로그인 페이지 (axios)

나도 오늘부터 개발자?! 2022. 8. 3. 21:14
<template>
  <div class="login" >
    <div>
      <h2>익명 게시판</h2>
      <!-- <span>로그인을 해주세요</span> -->
    </div>
    <div v-if="state.account.id">
      <p>안녕하세요? ~ {{state.account.name}}님 환영합니다</p>
      <button @click="logout">로그아웃</button>
    </div>
    <div v-else>
    <div>
      <p>아이디</p>
      <input
        id="loginId"
        v-model="state.form.loginId" 
        type="text"  
        placeholder="아이디" />
      <p>비밀번호</p>
      <input
        id="loginPw"
        v-model="state.form.loginPw" 
        type="password"
        placeholder="비밀번호" />
    </div>
    <div id="loginBut">
      <button @click="submit()">로그인하기</button>
    </div>
      <div id="buts">
        <button >아이디 찾기</button>
        <button>비밀번호 찾기</button>
        <button @click="signup">회원가입</button>
      </div>
  </div> 
</div> 
</template>

<script>
import { reactive } from "vue";
import axios from "axios"

export default {
  setup() {
    const state = reactive({
      account: {
        id: null,
        name: "",
      },
      form: {
        loginId: "",
        loginPw: "",
      },
    });
    const submit = () => {
      const args = {
        loginId: state.form.loginId,
        loginPw: state.form.loginPw,
      };
      axios
        .post("/api/account", args)
        .then((res) => {
          alert("로그인에 성공했습니다.");
          state.account = res.data;
        })
        .catch(() => {
          alert("로그인에 실패했습니다. 계정 정보를 확인해주세요.");
        });
    };
    const logout = () => {
      axios.delete("/api/account").then(() => {
        alert("로그아웃하였습니다.");
        state.account.id = null;
        state.account.name = "";
      });
    };
    axios.get("/api/account").then((res) => {
      state.account = res.data;
    });
    return { state, submit, logout };
  },
};
</script>
<style scoped>

.login {
  text-align: center;
}

#loginBut {
  margin-top: 3rem;
  margin-bottom: 2rem;
}

#buts {
  display: flex;
  justify-content: center;
}

</style>