无法从本地存储为Nuxt中的Auth初始化Vuex存储

时间:2019-12-11 00:02:13

标签: javascript vue.js local-storage vuex nuxt

我正在使用Nuxt.js,并且正在尝试进行自己的身份验证。它工作正常,但是当我刷新页面时,状态返回到初始数据,因此我尝试像这样从localStorage初始化Vuex存储:

export const state = () => ({ status: '', token: localStorage.getItem('token') || '', loggedInUser: localStorage.getItem('user') || '', })
但这给了我这个错误localStorage is not defined,但是localStorage.setItem在动作中效果很好

这是完整的代码:

import axios from 'axios'
export const state = () => ({
    status: '',
    token: localStorage.getItem('token') || '',
    loggedInUser: localStorage.getItem('user') || '',
})

export const getters = {
    status (state) {
        return state.status
    },
    authenticated (state) {
        return !!state.token
    },
    token (state) {
        return state.token
    },
    loggedInUser (state) {
        return state.loggedInUser
    },
}

export const mutations = {
    auth_request(state) {
        state.status = 'loading'
    },
    auth_success(state, token) {
        state.status = 'success'
        state.token = token
    },
    auth_error(state) {
        state.status = 'error'
    },
    logout(state) {
        state.status = ''
        state.token = ''
        state.loggedInUser = {}
    },
    auth_success2 (state, loggedInUser) {
        state.loggedInUser = Object.assign({}, loggedInUser)
    }
}

export const actions = {

    login({commit}, data) {
        return new Promise((resolve, reject) => {
            commit('auth_request')
            axios.post('http://127.0.0.1:8000/api/login', data)
                .then((res) => {
                    const loggedInUser = Object.assign({}, res.data.data)
                    const token = res.data.meta.token
                    localStorage.setItem('token', token)
                    localStorage.setItem('user', loggedInUser.name)
                    axios.defaults.headers.common['Authorization'] = 'Bearer '+ token
                    commit('auth_success', token)
                    commit('auth_success2', loggedInUser)
                    this.$router.push('/')
                    resolve(res)
                })
                .catch((error) => {
                    commit('auth_error')
                    console.log(error)
                    reject(error)
                })
        })
    }
}

1 个答案:

答案 0 :(得分:1)

您没有在其中抛出此错误,但我将假定它在您的服务器日志中。

正在发生的事情是Nuxt正在初始化自身服务器端,开始设置商店,并点击了localStorage声明。服务器没有本地存储,因此将失败。

要解决此问题,我建议使用带有.client后缀的插件,并在客户端初始化期间从localStorage获取值:

// the .client suffix is required here to tell nuxt to only run this client side.
// ~/plugins/vuex-init.client.js
export default ({ store }) => {
  const token = localStorage.getItem('token') || ''
  const loggedInUser = localStorage.getItem('user') || ''

  store.commit('setToken', token)
  store.commit('setUser', user)
}

如果您不想自己做这项工作,我以前使用过this,并取得了很好的效果。