Files
nl-blogs/blog-wot-uniapp/src/composables/useSearchHistory.ts
李琦 4e245f789b 1. 小程序端
2. 视频优化2
2026-07-30 14:14:28 +08:00

51 lines
1.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 思考页搜索历史:对齐 PC blog_search_history,最多 10 条。
* 小程序用 uni.setStorageSync,与 localStorage key 保持一致便于跨端对齐。
*/
export const SEARCH_HISTORY_KEY = 'blog_search_history'
const MAX_HISTORY = 10
export function useSearchHistory() {
/** 读取历史列表 */
const readHistory = (): string[] => {
try {
const raw = uni.getStorageSync(SEARCH_HISTORY_KEY)
if (!raw) return []
const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw
return Array.isArray(parsed) ? parsed.filter((item): item is string => typeof item === 'string') : []
}
catch {
return []
}
}
const writeHistory = (items: string[]) => {
uni.setStorageSync(SEARCH_HISTORY_KEY, JSON.stringify(items.slice(0, MAX_HISTORY)))
}
const getHistory = () => readHistory()
/** 写入关键词(去重置顶) */
const addHistory = (keyword: string) => {
const trimmed = keyword.trim()
if (!trimmed) return
const next = [trimmed, ...readHistory().filter(item => item !== trimmed)].slice(0, MAX_HISTORY)
writeHistory(next)
}
const removeHistory = (keyword: string) => {
writeHistory(readHistory().filter(item => item !== keyword))
}
const clearHistory = () => {
uni.removeStorageSync(SEARCH_HISTORY_KEY)
}
return {
getHistory,
addHistory,
removeHistory,
clearHistory,
}
}