在vuex中刷新或更改页面时保持用户状态

时间:2020-06-19 16:43:57

标签: javascript node.js vue.js authentication vuex

您可以看到我的用户状态一开始是空的,但是当用户登录时,我需要我的操作的用户ID setFavoriteCrypto

因此,我可以检索与连接的用户有关的特定数据,但是由于vuex每次刷新页面时都会初始化状态。用户为空

我知道有一个名为persist state的程序包,我可以使用它。

但是我想知道是否有一种不依赖软件包的方式来管理我的用户连接的方法?

我正在使用node.js作为此应用程序的后端。

import Api from '@/services/Api'
import axios from 'axios'

import router from '@/router'

const state = {
    localStorageToken: localStorage.getItem('user-token') || null,
    token: null,
    user: null,
    favoriteCrypto: []
}

const mutations = {
    setToken(state, token) {
        state.localStorageToken = token
        state.token = token
    },
    setUser(state, user) {
        state.user = user
    },
    setFavoritecrypto(state, crypto) {
        state.favoriteCrypto = crypto
    }
}

const actions = {
    setToken({commit}, token) {
        commit('setToken', token)
    },
    setUser({commit}, user) {
        commit('setUser', user)
    },
    setFavoriteCrypto({commit}, token) {
        if(state.user) {
            return Api().get('getuserfavoritescoins', {
                params: {
                    userId: state.user.id
                }
            })
            .then(response => response.data.coins)
            .then(cryptoFav => {
                commit('setFavoritecrypto', cryptoFav)
            })
        }
        else{
            console.log("there's not user state")
        }
    },
    loginUser({commit}, payload) {
        return Api().post('login', payload)
        .then(response => {
            commit('setUser', response.data.user)
            commit('setToken', response.data.token)

            localStorage.setItem('user-token', response.data.token)

            axios.defaults.headers.common['Authorization'] = response.data.token

            router.push('/main').catch(e => {})
        })
    },
    logoutUser({commit, dispatch})  {
        localStorage.removeItem('user-token')

        commit('setUser', null)
        commit('setToken', null)

        delete axios.defaults.headers.common['Authorization']
    }
}

const getters = {
    isAuthenticated: state => !!state.localStorageToken,
}

export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations
}

0 个答案:

没有答案