Good evening everyone, I would like you to guide me with my following problem:
What I want to do is save the sum of numbers in the localtorage This sum is entering an array called previous day, it enters localstorage without problem, in fact I can add by doing the push without problems until I reload the page, then when I enter a value again my array restarts what I want to do is that even if the browser reloads my values inside the array are preserved I hope you have explained a bit and I hope I have your help thank you very much
export default {
name: 'Form-main',
data: () => ({
uno: null,
dos: null,
cinco: null,
diez: null,
veinte: null,
cincuenta: null,
cien: null,
docientos: null,
quinientos: null,
resultado: null,
dialog: false,
diaAnterior:[],
ayer:[]
}),
methods: {
submit() {
this.sumaMonedas()
this.reset()
this.guardarDiaAnterior()
//localStorage.clear()
},
sumaMonedas() {
this.resultado = this.uno this.dos this.cinco this.diez this.veinte
this.cincuenta this.cien this.docientos this.quinientos
this.dialog = true
},
guardarDiaAnterior() {
this.diaAnterior.push(this.resultado)
localStorage.setItem('resultado',JSON.stringify(this.diaAnterior))
this.ayer= JSON.parse(localStorage.getItem('resultado'))
},
reset() {
this.uno= null
this.dos= null
this.cinco=null
this.diez= null
this.veinte= null
this.cincuenta= null
this.cien=null
this.docientos= null
this.quinientos= null
}
},
}
</script>
CodePudding user response:
Your values start again at zero because you constantly start from your this.diaAnterior
variable which, at each reload, becomes an empty array. So, you find yourself push
your new value into an empty array each time you reload.
You have to get the value of your localStorage, store it in this.diaAnterior
and then push
your result to add a new value to the old ones.
In code it would look like this:
guardarDiaAnterior() {
const resultStorage = JSON.parse(localStorage.getItem('resultado'))
if (resultStorage){
this.diaAnterior = resultStorage
}
this.diaAnterior.push(this.resultado)
localStorage.setItem('resultado',JSON.stringify(this.diaAnterior))
this.ayer= JSON.parse(localStorage.getItem('resultado'))
},