@datametria/vue-components
Version:
DATAMETRIA Vue.js 3 Component Library with Multi-Brand Theming - 51 components + 10 composables with theming support, WCAG 2.2 AA, dark mode, responsive system
27 lines (21 loc) • 528 B
text/typescript
import { ref, watch, type Ref } from 'vue'
export function useLocalStorage<T>(key: string, defaultValue: T): Ref<T> {
const storedValue = localStorage.getItem(key)
let parsedValue = defaultValue
if (storedValue) {
try {
parsedValue = JSON.parse(storedValue)
} catch {
parsedValue = defaultValue
}
}
const data = ref<T>(parsedValue) as Ref<T>
watch(
data,
(newValue) => {
localStorage.setItem(key, JSON.stringify(newValue))
},
{ deep: true }
)
return data
}