棋牌网站搭建公司如何制作网站教程
问题描述
今天在写项目用到localStorage进行存储并读取数据,并将读取到的数据存放到列表的时候,发现vue3不能直接对数组进行赋值。因为Vue3的响应式是proxy,对所有的数据进行了拦截。
onBeforeMount(() => {console.log(JSON.parse(localStorage.keywordList));
});
可以看出来JSON.parse()解析出来是一个数组,里面包含很多对象。
现在的问题变成了如何从数组中取出每个对象的值,并将它们存放到数组中。
加个数组下标,读取下标所在的对象
onBeforeMount(() => {console.log(JSON.parse(localStorage.keywordList)[0]);
});
想要取其中的value值
onBeforeMount(() => {console.log(JSON.parse(localStorage.keywordList)[0]._value);
});
解决方案
知道了取出一个_value的方法了,如何取出全部的?就要用到遍历了。
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 = [];}
});