UNPKG

chiyum-composable

Version:
141 lines (140 loc) 3.19 kB
import { ref, computed, watch, unref } from "vue"; function useCounter(initialValue = 0, options = {}) { const { min = -Infinity, max = Infinity, step = 1 } = options; const count = ref(initialValue); const doubleCount = computed(() => count.value * 2); const canIncrement = computed(() => count.value + step <= max); const canDecrement = computed(() => count.value - step >= min); const increment = () => { if (canIncrement.value) { count.value += step; } }; const decrement = () => { if (canDecrement.value) { count.value -= step; } }; const set = (value) => { if (value >= min && value <= max) { count.value = value; } }; const reset = () => { count.value = initialValue; }; return { count, doubleCount, increment, decrement, set, reset, canIncrement, canDecrement }; } function useLocalStorage(key, defaultValue) { const storedValue = localStorage.getItem(key); let initialValue; try { initialValue = storedValue ? JSON.parse(storedValue) : defaultValue; } catch { initialValue = defaultValue; } const value = ref(initialValue); const setValue = (newValue) => { value.value = newValue; }; watch( value, (newValue) => { try { localStorage.setItem(key, JSON.stringify(newValue)); } catch (error) { console.error(`Failed to save to localStorage:`, error); } }, { deep: true } // 深度監聽物件變化 ); return [value, setValue]; } function useDebounce(value, delay = 300) { const debouncedValue = ref(value.value); let timeoutId; watch(value, (newValue) => { clearTimeout(timeoutId); timeoutId = setTimeout(() => { debouncedValue.value = newValue; }, delay); }); return debouncedValue; } function useFetch(url) { const data = ref(null); const error = ref(null); const loading = ref(false); const execute = async () => { loading.value = true; error.value = null; try { const response = await fetch(url); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const result = await response.json(); data.value = result; } catch (err) { error.value = err instanceof Error ? err.message : "An error occurred"; } finally { loading.value = false; } }; return { data, error, loading, execute }; } function toValue(val) { return unref(val); } const isClient = typeof window !== "undefined"; const isLocalStorageSupported = () => { if (!isClient) return false; try { const testKey = "__localStorage_test__"; localStorage.setItem(testKey, "test"); localStorage.removeItem(testKey); return true; } catch { return false; } }; function safeJsonParse(str, fallback) { try { return JSON.parse(str); } catch { return fallback; } } const composables = { useCounter, useLocalStorage, useDebounce, useFetch }; export { composables, isClient, isLocalStorageSupported, safeJsonParse, toValue, useCounter, useDebounce, useFetch, useLocalStorage }; //# sourceMappingURL=index.es.js.map