웹앱프로젝트/Vue.js

Vuex 이용한 회원가입 구현 (vuex actions context의 사용)

Minah Park 2022. 8. 29. 12:54
반응형

흥미로운 아이를 발견함.

loginModule.js

import router from "@/router";
import axios from "axios";

const loginModule = {
    namespaced: true,    
      actions: {
        signUp(params){
          console.log('signup action activated')
          console.log(params)
           
        },
      },
}
export default loginModule;

MemberRegisterView.vue

<template>
  <b-container fluid>
    <h1>Sign Up</h1>
    <b-form>
      <b-form-group
        label="Name"
        label-for="username">
        <b-form-input
          type="text"
          id="username"
          placeholder="Enter name"
          v-model="user.username"
          v-validate="{required : true ,min:3, max:20}" />
      </b-form-group>

      <b-form-group
        label="Email"
        label-for="email">
        <b-form-input
          type="email"
          id="email"
          placeholder="Enter email address"
          v-model="user.email"
          v-validate="{required : true , max:50}" />
      </b-form-group>
      <b-form-group
        label="Password"
        label-for="password">
        <b-form-input
          type="password"
          id="password"
          placeholder="Enter password"
        
          v-model="user.password"
          v-validate="{required : true , min: 6 ,max:40}" />
      </b-form-group>
      <b-button
        variant="primary"
        @click="handleRegister">
        Sign Up
      </b-button>
    </b-form>
  </b-container>
</template>

<script>
export default {
  name: "MemberRegisterView",
  data() {
    return {
      user: {},
    };
  },
  methods: {
    handleRegister() {
      this.$store.dispatch("loginModule/signUp", this.user)
    },
  },
};
</script>

그래서 console을 확인해보면!!!

그래서 찾아보니,

Action handlers receive a context object which exposes the same set of methods/properties on the store instance, so you can call context.commit to commit a mutation, or access the state and getters via context.state and context.getters

이렇게 되어있다.

Action 은 context 객체를 받아야하는거다.

그 context 객체 안에는 commit, dispatch, getters  등이 들어있는거다! 

그래서 바꾼거!

loginModule.js

import router from "@/router";
import axios from "axios";

const loginModule = {
    namespaced: true,    
      actions: {
        signUp(context, params){
          console.log('signup action activated')
          console.log(params)
           
        },
      },
}
export default loginModule;

이렇게 actions 에 받는아이에 context를 넣으면, 

이렇게 콘솔창에 잘 뜬다!!!

 


회원가입으로 다시 돌아가면, 

axios 를 실행한 후에 backend 에서 쿼리를 실행하다 오류가 발생했을때, actions에서 아무것도 안하고 그냥 console에 에러만 발생하더라. 그래서 위에서 배운 try catch 를 넣어봤다. (에러 처리를 위해서)

loginModule.js

import router from "@/router";
import axios from "axios";

const loginModule = {
    namespaced: true,    
      actions: {
        async signUp(context, params){
          try{
            const res = await axios.post('/api/signUp/action',params);
            if(res.data.isSuccess == true){
              alert('회원가입이 완료되었습니다.');
            }else{
              alert('화원가입을 진행중 오류가 발생했습니다. 관리자에게 문의해주세요.');
            }
          }catch{
            alert('화원가입을 진행중 오류가 발생했습니다. 관리자에게 문의해주세요.');
          }
        },
      },
}
export default loginModule;

이렇게 했더니, 

 

alert창이 잘 떳다.

그런데 이제 생각해보니, 회원가입 전에 있는 이메일주소인지를 확인을 하고 넣어야하는데...? 라는 생각이 들었다.

그래서 그과정을 넣어보도록하겠다.

java에서 미리 확인해서 보내는 과정을 넣었다. 

// 회원가입
	@PostMapping(value = "/signUp/action")
	@ResponseBody
	public HashMap<String, Object> signUpAction(@RequestBody HashMap<String, Object> paramMap){
		HashMap<String, Object> returnMap = new HashMap<>();
		System.out.println(paramMap);
		if(paramMap != null) {
			// 일단 입력한 이메일주소가 이미 등록되었는지 확인하기
			int emailDupCheck = service.getCountMember(paramMap);
			if(emailDupCheck > 0) {
				returnMap.put("isSuccess", false);
				returnMap.put("errorMsg", "emailDup");
			}else {
				int result = service.addNewMemeber(paramMap);
				if(result == 1) {
					returnMap.put("isSuccess", true);
				}else {
					returnMap.put("isSuccess", false);
				}
			}
		}
		
		return returnMap;
	}

loginModule.js

import router from "@/router";
import axios from "axios";

const loginModule = {
    namespaced: true,    
      actions: {        
        async signUp(context, params){
          try{
            const res = await axios.post('/api/signUp/action',params);
            if(res.data.isSuccess == true){
              alert('회원가입이 완료되었습니다.');
            }else{
              if(res.data.errorMsg != null && res.data.errorMsg == 'emailDup'){
                alert('이미 등록된 이메일 주소입니다. 다시 입력해주세요.');  
              }else{
                alert('화원가입을 진행중 오류가 발생했습니다. 관리자에게 문의해주세요.');
              }
            }
          }catch{
            alert('화원가입을 진행중 오류가 발생했습니다. 관리자에게 문의해주세요.');
          }
        },
      },

}
export default loginModule;

이렇게 했는데.... 말이 안되는 것 같다. 왜냐면, 일단 vue 를 쓰는건 결국엔 frontend와 backend를 완전히 구분지어서 작업하는게 가능하게 한것인데. 결국엔 backend 개발자가 front를 건드리는 느낌..... 아니면 axios는 결국에는 backend의 작업이니 이게 맞는건가.... 잘모르겟다.

좀더 깔끔하게 사용하기 위해서, loginModule.js 에서는 확실하게 Vuex에 관한 것만 넣어놓고 싶기때문에, alert처럼 에러나 action에 대한 각각의 처리는 vue에서 하는게 맞는것같다 ( 이미 만들어져 있는 프로젝트를 참고해보면 ) -> 물어보고 시도해보겟다. 왜냐면, backend 에서 error로 넘겨줘야하는데... 잘모르겟다.

 

 

반응형