← Back to Vue.js Course | Chapter 9: Composables & Composition API | Lesson 4 of 7

useLocalStorage का Example

एक useLocalStorage composable एक ref को browser की local storage के साथ sync रखता है।

In this page:

  1. useLocalStorage Example
Syntax
markup
import { ref, watch } from 'vue';

export function useLocalStorage(key, initial) {
  const value = ref(JSON.parse(localStorage.getItem(key)) ?? initial);
  watch(value, (v) => localStorage.setItem(key, JSON.stringify(v)), { deep: true });
  return value;
}

useLocalStorage Example

Composable stored JSON को initial value की तरह पढ़ता है और हर change वापस लिखने के लिए watch इस्तेमाल करता है। क्योंकि यह एक ref return करता है, components इसे exactly normal state की तरह इस्तेमाल करते हैं और यह page reloads के बाद भी रहता है।

हमेशा JSON parsing guard करें और याद रखें storage सिर्फ strings hold करता है।

Note: Storage synchronous है और size में limited है, इसलिए values छोटी रखें।

उदाहरण: useLocalStorage example

markup
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
  <input v-model="name">
  <p>Hello, {{ name }}! (value is saved in localStorage)</p>
</div>
<script>
  function useLocalStorage(key, initial) {
    let start = initial;
    try { const raw = localStorage.getItem(key); if (raw !== null) start = JSON.parse(raw); } catch (e) {}
    const value = Vue.ref(start);
    Vue.watch(value, (v) => localStorage.setItem(key, JSON.stringify(v)), { deep: true });
    return value;
  }
  Vue.createApp({
    setup() {
      const name = useLocalStorage("username", "Ada");
      return { name };
    },
  }).mount("#app");
  const i = document.querySelector("input");
  i.value = "Grace"; i.dispatchEvent(new window.Event("input"));
  setTimeout(() => console.log("saved in storage:", localStorage.getItem("username")), 50);
</script>
</body>
</html>

<!-- Output:
Rendered: Hello, Grace! (value is saved in localStorage)
console: saved in storage: "Grace"
-->
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. sensitive data store करना
  2. invalid JSON handle न करना
  3. objects के लिए deep: true भूल जाना
चैप्टर सारांश
  • Storage से initial value पढ़ें
  • watch changes वापस लिखता है
  • एक normal ref return करता है
  • JSON parsing guard करें
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.