← Totes les receptes·Composables
Un ref que es desa sol
Preferències, esborranys, l'últim filtre… Aguanta recàrregues, se sincronitza entre pestanyes i no trenca el render al servidor.
TypeScript
import { onMounted, onUnmounted, ref, watch, type Ref } from "vue";
/**
* A ref that lives in localStorage: survives reloads and stays in sync
* between tabs. Reads after mount, so server rendering never touches it.
*/
export function useLocalStorage<T>(key: string, initial: T): Ref<T> {
const value = ref(initial) as Ref<T>;
const read = () => {
try {
const saved = localStorage.getItem(key);
if (saved !== null) value.value = JSON.parse(saved);
} catch {
/* Private mode or broken JSON: keep the initial value. */
}
};
const onStorage = (event: StorageEvent) => {
if (event.key === key) read();
};
onMounted(() => {
read();
window.addEventListener("storage", onStorage);
});
onUnmounted(() => window.removeEventListener("storage", onStorage));
watch(
value,
(next) => {
try {
localStorage.setItem(key, JSON.stringify(next));
} catch {
/* Full or blocked: the ref still works for this visit. */
}
},
{ deep: true },
);
return value;
}
Vue SFC
<script setup lang="ts">
import { useLocalStorage } from "./useLocalStorage";
const name = useLocalStorage("vue-demo-name", "");
const done = useLocalStorage("vue-demo-done", [false, false, false]);
</script>
<template>
<label>
Tu nombre
<input v-model="name" placeholder="Recarga y sigue aquí" />
</label>
<p v-if="name">Hola, {{ name }} 👋</p>
<label v-for="(_, i) in done" :key="i">
<input v-model="done[i]" type="checkbox" /> Tarea {{ i + 1 }}
</label>
</template>