programing

모듈 및 vuex-persisted state를 사용한 Vuex 상태 유지

goodsources 2022. 8. 31. 22:53
반응형

모듈 및 vuex-persisted state를 사용한 Vuex 상태 유지

vue에서 인증 구현 작업을 진행 중인데 새로 고침 시 상태가 손실되어 jwt 토큰이 지워집니다.우연히 알게 되었다vuex-persistedstate모듈로 사용할 때 구문을 제대로 알 수 없는 것 같습니다.어떻게 하면 더 이상 참을 수 없을까?token그리고.status내 상태auth.js모듈?

로컬 스토리지로 이동하면 상태가 추가되는 것처럼 보이지만 페이지를 새로 고치면 지속되지 않습니다.

index.displaces를 표시합니다.

import Vue from 'vue';
import Vuex from 'vuex';
import * as auth from '@/store/modules/auth'
import createPersistedState from 'vuex-persistedstate'

Vue.use(Vuex);

const authState = createPersistedState({
  paths: ['auth']
})

export default new Vuex.Store({
  modules: {
    auth
  },
  plugins: [authState],
});

auth.displays(인증)

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

Vue.use(Vuex);

// https://scotch.io/tutorials/handling-authentication-in-vue-using-vuex
export const state = {
  status: '',
  token: localStorage.getItem('token') || '',
  user : {}
}

//update state synchronously 
//**mutations should always be abstracted out and put into actions**
export const mutations = {
  AUTH_REQUEST(state){
    state.status = 'loading'
  },
  AUTH_SUCCESS_TOKEN(state, token){
    state.token = token
  },
  AUTH_SUCCESS_USER(state, user){
    state.user = user
  },
  AUTH_SUCCESS_STATUS(state, status){
    state.status = status
  },
  AUTH_ERROR(state){
    state.status = 'error'
  },
  LOGOUT(state){
    state.status = ''
    state.token = ''
  },
}

// acts like global computed methods
export const getters = {
  isLoggedIn: state => !!state.token,
  authStatus: state => state.status,
}

//asynchronously wrap business logic around mutations. 
export const actions = {
  login({commit, dispatch}, user){
    return new Promise((resolve, reject) => {
      commit('AUTH_REQUEST');
      axios({url: 'http://localhost:5000/api/auth/authenticate', data: user, method: 'POST' })
      .then(resp => {
        const token = resp.data.token;
        const user = resp.data.user;
        localStorage.setItem('token', token);
        
        axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
        dispatch("authSuccess", { token, user }); 
        resolve(resp);
      })
      .catch(err => {
        commit('AUTH_ERROR');
        localStorage.removeItem('token');
        reject(err);
      })
    })
  },
  authSuccess({ commit }, {token ,user}){
    commit('AUTH_SUCCESS_STATUS', 'success');
    commit('AUTH_SUCCESS_TOKEN', token);
    commit('AUTH_SUCCESS_USER', user);
  },
  register({ commit, dispatch }, user){
    return new Promise((resolve, reject) => {
      commit('AUTH_REQUEST');
      axios({url: 'http://localhost:5000/register', data: user, method: 'POST' })
      .then(resp => {
        const token = resp.data.token;
        const user = resp.data.user;
        localStorage.setItem('token', token);
        axios.defaults.headers.common['Authorization'] = token;

        dispatch("authSuccess", { token, user }); 
        resolve(resp);
      })
      .catch(err => {
        commit('AUTH_ERROR', err)
        localStorage.removeItem('token')
        reject(err)
      })
    })
  },
  logout({ commit }){
    return new Promise((resolve, reject) => {
      commit('LOGOUT')
      localStorage.removeItem('token')
      delete axios.defaults.headers.common['Authorization']
      resolve()
      window.sessionStorage.clear();
    })
  }
}

export const modules = {
}

언급URL : https://stackoverflow.com/questions/62845067/persisting-vuex-state-with-modules-and-vuex-persistedstate

반응형