无法从本地存储读取 vuex 存储模块中 null 的属性'id'



我有一个用于Currentuser的商店模块。基本上,在登录到应用程序后,我保留了用户数据。但是,当我注销时,我将重定向到登录页面,并从登录时从localstorage中删除当前用户数据。

但是,一旦我登录,我在控制台中会遇到此错误:

无法读取null的属性'id'

这是因为我如何在当前使用者模块中初始化值的初始化值,如下所示:

const currentUser = {
    state: {
        id: JSON.parse(localStorage.getItem('current-user')).id || '',
        username: JSON.parse(localStorage.getItem('current-user')).username || '',
    },

因此,它试图访问由于我在注销时将其删除以来不再存在的localstorage对象。处理此问题的最佳方法是什么?我是Vue的新手,因此不确定我在做什么,即使一开始就可以做一件好事。

尝试此

const currentUser = {
        state: {
            id:JSON.parse(localStorage.getItem('current-user')) && JSON.parse(localStorage.getItem('current-user')).id || '',
            username: JSON.parse(localStorage.getItem('current-user')).username || '',
        }

,如果涉及任何逻辑,我认为Getters将是一个更好的解决方案(即使它只是检查存在)。

尝试:

const curentUser = {
  getters: {
    id() {
      const cu = localStorage.getItem('current-user');
      if (cu) {
        return JSON.parse(cu).id;
      }
      return '';
    },
    username() {
      const cu = localStorage.getItem('current-user');
      if (cu) {
        return JSON.parse(cu).username;
      }
      return '';
    }
  }
}

最新更新