vue.js/vue.js 2

119. 로그아웃 기능 구현 | mutations에 clearUsernmae 함수 추가

DEV-Front 2023. 1. 24. 19:50
반응형

1. vuex | mutations에 clearUsernmae 함수 추가 

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  // store에서 state 는 여러 컴포넌트 간에 공유되는 데이터를 뜻한다.
  state: {
    username: '',
  },
  // state의 값이 변경됬을때 특정 상태를 개선할수 있게 사용가능
  // getters의 첫번쨰 인자는 state
  // getters는 기본적으로 return값을 가지고 있음
  getters: {
    // username이 빈 문자열이면 로그인 안된상태
    // 로그인 되면(빈문자열이 아니면) getters가 true로 바뀜
    isLogin(state) {
      return state.username !== '';
      // 로그인전엔 false, 로그인 후엔 true를 보내주는것
    },
  },
  // mutations은 state의 값을 바꿀수 있는 유일한 방법이다.
  // mutations의 첫번째 인자는 state고, 두번째 인자는 호출할때 넘기는 값을 의미한다.
  // username을 받아서 state가 호출될때 username을 넘기겠단 뜻
  mutations: {
    setUsername(state, username) {
      state.username = username;
    },
    clearUsernmae(state) {
      //로그아웃 함수
      state.username = '';
    },
  },
});

2. AppHeader 컴포넌트 methods에 logoutUser() 함수 추가

- @click="logoutUser" 클릭 시 로그아웃 함수가 실행되게 한다.

<template>
  <header>
    <div>
      <router-link to="/" class="logo">
        TIL
      </router-link>
    </div>

    <div class="navigations">
      <!-- 태그 분기 처리해야함. 이럴때 template 사용-->
      <!-- 1 -->
      <!-- <template v-if="$store.getters.isLogin">
        <span>{{ $store.state.username }}</span>
      </template> -->
      <template v-if="isUserLogin">
        <span class="username">{{ $store.state.username }}</span>
        <a href="javascript:;" @click="logoutUser">Logout</a>
      </template>
      <!-- 2 -->
      <template v-else>
        <router-link to="/login">로그인</router-link>
        <router-link to="/signup">회원가입</router-link>
      </template>
    </div>
  </header>
</template>

<script>
export default {
  computed: {
    isUserLogin() {
      return this.$store.getters.isLogin;
    },
  },
  methods: {
    logoutUser() {
      this.$store.commit('clearUsernmae');
      this.$router.push('/');
    },
  },
};
</script>

<style scoped>
header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background-color: #927dfc;
  z-index: 2;
  box-shadow: 0px 3px 10px rgba(0, 0, 0, 0.05);
}
a {
  color: #dedede;
  font-size: 18px;
}
a.logo {
  font-size: 30px;
  font-weight: 900;
  color: white;
}
.logo > span {
  font-size: 14px;
  font-weight: normal;
}
.navigations a {
  margin-left: 10px;
}
.fixed {
  position: fixed;
  top: 0;
  width: 100%;
}
a.router-link-exact-active {
  color: white;
  font-weight: bold;
}

.username {
  color: #fff;
}
</style>

3. 완성

로그아웃 버튼

 

로그아웃 후 메인으로 이동

반응형