Home > Mobile >  Saving array and objects within said array
Saving array and objects within said array

Time:11-03

I am trying to make a simple to do app using vue.js, I want to try and save my to-dos that are set in the array so that when I reset the site, they still remain. Looking through some of the documentation I arrived at this:

data() {
        return {
            array: [
                 {id: 1, label: 'learn vuejs'},
            ]
        }
    }, 
methods: {
        persist() {
            localStorage.array = this.array;
            alert('items saved')
        }
    },
mounted() {
        if (localStorage.array && localStorage.array.id) {
            this.array = localStorage.array;
            this.array[id] = localStorage.array.id;
        }
    },

while this does save my array to localStorage, IT DOES NOT THE OBJECTS WITHIN. When I check localStorage in the console it shows :

array: "[object Object]"

anyone knows how to save the items within the array? if you do please explain it to me.

CodePudding user response:

You need to store them as string. So localStorage.array = JSON.stringify(this.array), and when fetching from localStorage this.array = JSON.parse(localStorage.array);

  • Related