'Get Values of Nested Objects from localStorage Vue.js
I have a vue.js application and into a component there's the data method that's returns a nested object like this:
obj: {
color: {
value: '',
},
shape: {
value: '',
},
size: {
value: '',
},
}
Into the template a have inputs with v-models to fill these values:
<template>
<input
v-model = "obj.color.value"
/>
<input
v-model = "obj.shape.value"
/>
<input
v-model = "obj.size.value"
/>
I can save this values into localStorage with the JSON.stringify method:
methods {
save() {
localStorage.setItem("Itens", JSON.stringify(this.obj))
}
}
and I can get this values from the localStorage with the JSON.parse:
created() {
this.obj = JSON.parse(localStorage.getItem("Itens"))
}
However, when I do this into created the input fields into template aren't filled automatically with the values of obj saved in localStorage, the fields still blank. How can I get these values saved into the localStorage e fill the fields automatically with this stored values?
Solution 1:[1]
Vue does not detect changes in a nested object. You'll have to create a watcher like so:
watch: {
object: {
handler(newVal, oldVal) {
// do something with the object
},
deep: true,
},
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
