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

Composables का Pattern

एक composable एक function है जो reusable stateful logic package करने के लिए Composition API features इस्तेमाल करता है।

In this page:

  1. Composables Pattern
Syntax
markup
import { ref } from 'vue';

export function useName() {
  const state = ref(initial_value);
  function update() { state.value++; }
  return { state, update };
}

const { state, update } = useName();

Composables Pattern

Convention से composables use से शुरू होते हैं, जैसे useCounter या useMouse। ये अंदर refs, computed values, और watchers बनाते हैं और इन्हें return करते हैं।

कोई भी component composable call कर सकता है, अपनी independent state पाते हुए, जो mixins की जगह clearer, explicit reuse से लेता है।

Note: Composables से refs return करें ताकि callers इन्हें safely destructure कर सकें।

उदाहरण: Composables pattern

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">
  <counter-a></counter-a>
  <counter-b></counter-b>
</div>
<script>
  function useCounter(start = 0) {
    const count = Vue.ref(start);
    const increment = () => count.value++;
    const doubled = Vue.computed(() => count.value * 2);
    return { count, increment, doubled };
  }
  const app = Vue.createApp({});
  app.component("counter-a", { setup: () => useCounter(0), template: '<button @click="increment">A: {{ count }} ({{ doubled }})</button>' });
  app.component("counter-b", { setup: () => useCounter(100), template: '<button @click="increment">B: {{ count }} ({{ doubled }})</button>' });
  app.mount("#app");
  document.querySelector("button").click();
  Vue.nextTick(() => console.log([...document.querySelectorAll("button")].map((b) => b.textContent).join(" | ")));
</script>
</body>
</html>

<!-- Output:
Rendered: A: 1 (2)B: 100 (200)
console: A: 1 (2) | B: 100 (200)
-->
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. module-level refs के जरिए accidentally state share करना
  2. use prefix भूल जाना
  3. refs की बजाय plain values return करना
चैप्टर सारांश
  • Composables use-functions हैं
  • ये refs और functions return करते हैं
  • हर caller को अपनी state मिलती है
  • ये mixins की जगह लेते हैं
🔒

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.