-
Vuex의 Store 이해하고 사용해보기 (로그인 토큰 저장)Web/Frontend 2020. 7. 24. 13:50
vuex - vue 전역에서 사용할 전역변수를 관리해주는 라이브러리
store - 전역변수
state - 값을 저장하는 객체
getters - state의 값을 반환하는 함수, computed 속성과 매칭되는 기술요소
actions - mutations 에 값을 보내는 함수
mutations - setter , state의 값을 변경하는 함수
computed 속성이란. 기본적으로 getter역할 , 캐싱된 데이터가 있다면 즉시 반환.
filter(), reverse() 등의 추가적인 계산 로직이 들어갈 때 장점이 발휘된다.
(watch와의 차이점 : watch 속성은 감시할 데이터를 지정하고 그 데이터가 바뀌면 이런 함수를 실행하라는 방식
반면 computed는 호출할때 실행)
import { mapActions, mapGetters } from 'vuex' //1 computed:{ ...mapGetters([ 'getUser', // 여기서 getUser는 getters에서 선언된 속성 이름 ]), }, //2 computed: mapGetters([ 'getUser' ]), //3 computed: mapGetters({ getUser : 'getUser' }), //4 computed: { getUser() { this.$store.getters.getUser; } },1,2,3,4 모두 같은 역할을 수행한다.
1,2,3은 mapGetters를 활용한 코드이다.
2번과 3번은 1번과 동일한 코드이지만
컴포넌트 자체에서 다른 computed 속성과 함께 사용하지 못하는데
이에 해결방안으로 ES6 의 문법 ... 을 사용하면 된다.
... 문법을 사용하려면 Babel stage-2 라이브러리 설치 및 babel preset 에 추가가 필요하다.
비슷한 방식으로
methods: { // Actions 를 이용할 때 AC_USER() { this.$store.dispatch('AC_USER'); } // 위와 동일한 코드 mapActions 사용 ...mapActions([ 'AC_USER', ]) },//
추가될내용.
actions = dispatch
mutations = commit
??
//
토큰값 저장해보기.
main.js 에
import store from './vuex/store'; 추가
store.js이 존재하는 폴더 내에 index.js 파일 추가
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) // 작성한 모듈을 가져옵니다. import Store from '@/vuex/store.js' const store = new Vuex.Store({ modules: { // 키: 값 형태로 저장됩니다. Store: Store, } }) export default storestore.js 부분
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { user:{}, }, getters: { getUser(state) { return state.user; }, }, mutations:{ LOGIN(state,data){ state.user=data; }, LOGOUT(state){ state.user=null; } }, actions:{ AC_USER:({commit},payload)=>{ commit('LOGIN',payload) } } })Login.vue
<script> import axios from 'axios'; import { mapActions, mapGetters } from 'vuex' const Store='Store' export default { name: 'Login', modules:{ store:Store }, data () { return { email: '', password: '', } }, computed:{ ...mapGetters([ 'getUser', ]), }, methods: { ...mapActions(['AC_USER']), loginHandler() { console.log(this.email); console.log(this.password); axios.get('http://localhost:8080/account/login',{ params:{email:this.email, password:this.password}, }).then((response)=>{ // 로그인 성공 if(response.data.result==1){ this.AC_USER(response.data); console.log(this.getUser); } // 이메일 없음 else if(response.data.result==-1){ alert("이메일이 존재하지 않습니다."); } // 비밀번호 틀림 else if(response.data.result==2){ alert("비밀번호가 틀립니다."); } }); }, } } </script>백엔드를 거쳐서 온 정보들을 state에 저장하고
state의 정보들을 불러와 console 찍으면 다음과 같이 출력된다.

'Web > Frontend' 카테고리의 다른 글
Vue 라이프 사이클 (0) 2020.08.04