반응형
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. 완성
반응형
'vue.js > vue.js 2' 카테고리의 다른 글
121. Main Page - 학습 노트 조회 API 함수 구현 | v-for로 Data 바인딩 (0) | 2023.02.05 |
---|---|
120. Request 요청에 Token 넣어서 API 가져오기 | 액시오스 인터셉터 | 인터셉터 모듈화 (0) | 2023.01.24 |
118. 로그인 후 처리 | 컴포넌트 간 데이터 전달방법 3가지 | vuex store 사용 (0) | 2023.01.24 |
117. 로그인 후 Main 페이지 이동 | this.$router.push('/main'); (0) | 2023.01.18 |
116. 사용자 폼 유효성 검사 | email 방식인지 체크 | :disabled="!isUsernameValid || !password" (0) | 2023.01.18 |