When to invoke localStorage

Asked 2 years ago, Updated 2 years ago, 110 views

Problems

I'm running a simple app on vue.js, but the timing of calling localStorage is not good.

Error points

I think I'm calling localStorage with the code below, but the data disappears.

 mounted:function(){
    This.items=JSON.parse(localStorage.getItem('items'))||[];
  },

Source Codes Affected

<divid="app">
    <ul v-for = "item in items" >
      <li>{{item.id}}</li>
    </ul>
    <p@click="addItem">
     Click to add
    </p>
 </div>
varvue=newVue({
    el: '#app',
  data: {
      items:
     {id:'a', text:'aaa'},
     {id:'b', text:'bbb'}
    ]
  },
  methods: {
    addItem: function(){
     let todo={id:'c', text:'cc'}
      This.items.push(todo)
    }
  },
  watch: {
    items: {
      handler:function(){
        localStorage.setItem('items', JSON.stringify(this.items));
      },
      deep —true
    }
  },
  mounted: function() {
    This.items=JSON.parse(localStorage.getItem('items'))|[];
  },
})

Tried

I thought the mounted timing was wrong, so I tried various vue.js lifecycles, but it didn't work.

URL

URL for github
https://github.com/kondo97/demo.git

Verification URL
https://kondo97.github.io/demo/

Other

It would be very helpful if you could let me know if anyone understands.
Thank you for your cooperation.

Add

This post is multi-posted.
https://teratail.com/questions/350335#reply-479899

javascript vue.js

2022-09-30 17:05

1 Answers

Do the following with no data in LocalStorage

JSON.parse(localStorage.getItem('items')))
=>null

Run null and empty bit OR to 0

 null | [ ]
= > 0

Error in push method call because initialization replaced 0 with items

Logical sum (||) will do as expected

this.items=JSON.parse(localStorage.getItem('items')))||[];

add
Clear local storage once fixed (because items have been saved)
Open the site and run localStorage.clear() on the developer tool console


2022-09-30 17:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.