import storage from "../../plugins/storage";
|
|
export const STORAGE_KEYS = {
|
SEARCH_HISTORY: 'film:search:history',
|
USER_TOKEN: 'film:user:token',
|
// 你可以继续拓展其他常量
|
}
|
|
export function getSearchHistory(): string[] {
|
const history = storage.getItem(STORAGE_KEYS.SEARCH_HISTORY)
|
return history ? JSON.parse(history) : []
|
}
|
|
export function addSearchHistory(keyword: string) {
|
// 去除前后空格
|
const trimmed = keyword.trim()
|
if (!trimmed) return // 空字符串不保存
|
|
let history = getSearchHistory()
|
|
// 如果已经存在就不保存
|
if (history.includes(trimmed)) return
|
|
history = [trimmed, ...history]
|
|
// 限制最多保留10条
|
if (history.length > 10) history = history.slice(0, 10)
|
|
storage.setItem(STORAGE_KEYS.SEARCH_HISTORY, JSON.stringify(history))
|
}
|
|
export function clearSearchHistory() {
|
storage.removeItem(STORAGE_KEYS.SEARCH_HISTORY)
|
}
|
|
/**
|
* 根据索引删除某一项搜索历史
|
* @param index 要删除的项的索引
|
*/
|
export function removeSearchHistoryByIndex(index: number) {
|
const history = getSearchHistory()
|
|
if (index < 0 || index >= history.length) return // 防止越界
|
|
history.splice(index, 1) // 删除指定索引的项
|
|
storage.setItem(STORAGE_KEYS.SEARCH_HISTORY, JSON.stringify(history))
|
}
|