本地存储存储和读取到的内容都是字符串,只能先把要存储的数据放到一个空的数组里,在通过转换成字符串后,再存储到本地存储中。
1.在data定义数据
searchValue:'', //搜索框的value
searchHistory:[] //搜索的val存到这个数组
2.判断这个key是否有本地的存储,有的话就读取,并赋值给空数组,没有就设置一个空的‘数组’
if( !localStorage.getItem('searchList')){
//没有设置一个
localStorage.getItem('searchList', '[]')
}else{
//有读取,读取到的值,赋值给searchHistory
this.searchHistory = JSON.parse( localStorage.getItem('searchList') )
}
3.每次搜索先存到数组里面,去重、转换类型后再存储到本地存储里
// 将每次搜索的值添加到数组里的首位
this.searchHistory.unshift(this.searchVal);
// 数组去重,但是去重后得到的是一个对象
let historyArr = new Set(this.searchHistory)
// 把去重后的对象先转换成真正的数组,在转换成字符串,最后再存储到本地存储里
localStorage.setItem('searchList', JSON.stringify(Array.from(historyArr)) )
这样就存储起来了
4.使用,在搜索页面读取到这个本地存储的值,再循环展示就可以了
//读取到这个值,同时赋值给一个数组,再循环展示在页面就行了。
this.searchHistory = JSON.parse( localStorage.getItem('searchList') )