[Vue3] Problem with localStorage reading array and assigning value

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));
});

Insert image description here
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]);
});

Insert image description here
Want to get the value

onBeforeMount(() => {
    
    
  console.log(JSON.parse(localStorage.keywordList)[0]._value); 
});

Insert image description here


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 = [];
  }
});

Insert image description here

Guess you like

Origin blog.csdn.net/2201_75499330/article/details/129727351