简体   繁体   中英

How to save a array object into Chromes local storage

I am building a Budget-Calculator-App which should save the user data into chromes local storage. Idea is that everyone can use this app from his device whiteout a need of a database.

I am stuck on saving my whole data state into the local storage. I did a screenshot to show what i mean and what i get instead of the array of objects. 预览我的输出是什么

As you can see i am not getting the array saved and i don't know why.


Here is the code:

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

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    users: [
      {
        userName: 'John',
        salary: 2000,
        leftover: 0,
        active: false,
        inc: [],
        exp: []
      }
    ]
  },
  getters: {
    users: state => {
      return state.users;
    }
  },
  mutations: {
    addNewUser: (state, payload) => {
      state.users.push(payload);
    }
  },
  actions: {
    saveStateInStorage: (context, payload) => {
      context.commit('addNewUser', payload);
      // save current state into chrome local storage
      console.log(context.state.users);
      let userData = context.state.users;
      localStorage.setItem('budgetCalcUserData', userData);
    },
    updateStorageState: context => {
      console.log(context);
    }
  },
  modules: {}
});

All works fine except the saving into the local storage.

You should store the stringified array:

Try

localStorage.setItem('budgetCalcUserData', JSON.stringify(userData));

When access you have to parse that:

var user = JSON.parse(localStorage.getItem('budgetCalcUserData'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM