Files
tools-app/src/composables/useLocalStorage.js

19 lines
550 B
JavaScript

import { ref, watch } from 'vue'
export function useLocalStorage(key, defaultValue) {
// Initialize state from local storage or default value
const storedValue = localStorage.getItem(key)
const data = ref(storedValue ? JSON.parse(storedValue) : defaultValue)
// Watch for changes and update local storage
watch(data, (newValue) => {
if (newValue === null || newValue === undefined) {
localStorage.removeItem(key)
} else {
localStorage.setItem(key, JSON.stringify(newValue))
}
}, { deep: true })
return data
}