강디너의 개발 일지

프로젝트_v8 Vue Login 기능 만들기 본문

Javascript/토이프로젝트

프로젝트_v8 Vue Login 기능 만들기

강디너 2019. 2. 5. 00:39
728x90
반응형

준비물

 

1. express 서버 키기

2. mysql 서버 키기

3. Vue 서버 키기

 

 

*설치 모듈*

 

서버와 통신하기 위한 axios 설치

상태 관리를 위한 Vuex 설치

 

 

Login 기능 만들기 + 인증

 

1. axios를 main.js 에 넣어서 전역으로 쓸수 있게 합니다.

 

 

2. 로그인을 해봅시다.

 loginSubmit: function() {
      console.log("로그인");
      this.$Axios.post(`http://127.0.0.1:3000/auth/login`, { id: this.user_id, pwd: this.user_pwd}).then(
        res=> {
          console.log(res);
          this.$router.push("/");
        }
      )
    },

 

리턴값이 이쁘게 나오는 것을 볼 수 있습니다.

 

 

3. 상태 관리를 위하여 vuex 셋팅

 

 

4. vuex도 전역으로 셋팅

 

 

5. vuex 활용

 

loginSubmit: function() {
      console.log("로그인");
      this.$Axios.post(`${this.$store.state.host}/auth/login`, { id: this.user_id, pwd: this.user_pwd}).then(
        res=> {
          console.log(res);
          this.$router.push("/");
        }
      )
    },

 

6. vuex 에 이제 기능을 많이 넣습니다.

토큰 저장 하는 기능, 로그아웃 기능, 로그인 체크 기능이 있습니다.

체크 기능에는 가지고있는 토큰을 보내서 토큰의 정보를 확인하는 기능입니다.

 

 

 

토큰 정보.

 

 

7. Login.vue 코드

 

Login page에 오면 자동으로 로그아웃 되게끔 하고,

commit을 이용해서 받아온 token을 저장합니다.

 

 

8. Home.vue

<template>
  <div id="home">
    <div>
      {{$store.state.id}}님 안녕하세요.<br>
      여기는 홈 입니다.<br>
      당신의 권환은 {{$store.state.role}} 입니다.
     </div>
  	<button class="btn" v-on:click="goAdmin">Admin</button>
  </div>
 </template>

 <script>
 export default {
  
  created() {
  	this.$store.commit('userCheck');
  },
  methods: {
  	goAdmin: function() {
 	 	console.log("어드민으로 가기");
  		if (this.$store.state.role == "admin") {
  			this.$router.push("/Admin");
  		}
  	}
  }
 };
</script>

9. Admin

<template>
  <div id="home">
    <div>
      안녕하세요<br>
      여기는 어드민 페이지 입니다.
    </div>
    <div>
      <button class="btn" v-on:click="goHome">Home</button>
    </div>
  </div>
</template>

<script>
export default {
  created() {
 	 this.$store.commit("userCheck");
  },
  methods: {
  	goHome: function() {
  		this.$router.push("/");
  	}
  }
};
</script>

 

 

 

 

 

버튼 클릭시 왔다갔다 하는 것을 볼 수 있습니다.

 

 

 

 

커피한잔...
Comments