笔者vue项目有一个需求,搜索框添加历史搜索记录。想着很久没更新博客了,记录一下吧。
PS:pinia+vue3+vant+ts,或许你在使用vue2的语法,不要紧,可以根据自己的需求简单改改。
效果图
正文
搜索框的逻辑就不介绍了,今天这个问题其实是vue操作localStorage。笔者先写了一个工具类来完成对缓存的操作:
export class CacheManager {
static getHomeSearchHistoryWords() {
return localStorage.getItem("home-search-history-words")?.split(",") ?? [];
}
static setHomeSearchHistoryWords(words: string) {
return localStorage.setItem("home-search-history-words", words);
}
static clearHomeSearchHistoryWords() {
localStorage.removeItem("home-search-history-words");
}
}
- 双问号的作用是左表达式为空或undefined时,会取右表达式的值
- getHomeSearchHistoryWords 为读取历史搜索记录,返回值为数组;setHomeSearchHistoryWords 为写入,参数为String类型;clearHomeSearchHistoryWords 为清空。