You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

37 lines
1.2 KiB

export function useSearch() {
const results = ref<any[]>([]);
const suggestions = ref<string[]>([]);
const loading = ref(false);
const history = ref<string[]>([]);
// Load search history from localStorage
if (process.client) {
try {
history.value = JSON.parse(localStorage.getItem('search_history') || '[]');
} catch { history.value = []; }
}
function addToHistory(q: string) {
if (!q.trim()) return;
history.value = [q, ...history.value.filter(h => h !== q)].slice(0, 20);
if (process.client) localStorage.setItem('search_history', JSON.stringify(history.value));
}
async function search(q: string) {
if (!q.trim()) { results.value = []; return; }
loading.value = true;
addToHistory(q);
try {
const res = await $fetch<any>('/api/search', { params: { q } });
if (res.code === 0) results.value = res.data;
} finally { loading.value = false; }
}
async function fetchSuggestions(q: string) {
if (!q.trim()) { suggestions.value = []; return; }
const res = await $fetch<any>('/api/search/suggest', { params: { q } });
if (res.code === 0) suggestions.value = res.data;
}
return { results, suggestions, loading, history, search, fetchSuggestions };
}