tj
2025-05-30 d9a780fa538cb7a83aefa04e75cb53185d690d7d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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))
  }