I'm running a simple app on vue.js, but the timing of calling localStorage is not good.
I think I'm calling localStorage with the code below, but the data disappears.
mounted:function(){
This.items=JSON.parse(localStorage.getItem('items'))||[];
},
<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'))|[];
},
})
I thought the mounted timing was wrong, so I tried various vue.js lifecycles, but it didn't work.
URL for github
https://github.com/kondo97/demo.git
Verification URL
https://kondo97.github.io/demo/
It would be very helpful if you could let me know if anyone understands.
Thank you for your cooperation.
This post is multi-posted.
https://teratail.com/questions/350335#reply-479899
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
586 PHP ssh2_scp_send fails to send files as intended
926 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
575 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
622 GDB gets version error when attempting to debug with the Presense SDK (IDE)
© 2024 OneMinuteCode. All rights reserved.