Problem Description
Today, when I was writing a project that used localStorage to store and read data, and stored the read data in a list, I found that vue3 cannot directly assign values to arrays. Because the responsiveness of Vue3 is proxy, all data is intercepted.
onBeforeMount(() => {
console.log(JSON.parse(localStorage.keywordList));
});
It can be seen that JSON.parse() parses an array containing many objects.
The question now becomes how to get the value of each object from the array and store them into the array.
Add an array subscript and read the object where the subscript is located
onBeforeMount(() => {
console.log(JSON.parse(localStorage.keywordList)[0]);
});
Want to get the value
onBeforeMount(() => {
console.log(JSON.parse(localStorage.keywordList)[0]._value);
});
solution
Now that I know how to retrieve one _value, how do I retrieve all of them? It is necessary to use traversal.
const keywordList = reactive([]);
onBeforeMount(() => {
let res = localStorage.keywordList;
if (res) {
for (let [index, elem] of JSON.parse(localStorage.keywordList).entries()) {
keywordList.push(elem._value)
}
} else {
keywordList = [];
}
});