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

setup() का उपयोग

setup Composition API का entry point है: यह component बनने से पहले चलता है और वह return करता है जो template इस्तेमाल कर सकता है।

In this page:

  1. setup()
Syntax
markup
export default {
  setup() {
    const name = ref(initial_value);
    const doubled = computed(() => name.value * 2);
    function method() { name.value++; }
    return { name, doubled, method };
  }
}

setup()

setup के अंदर आप ref और reactive से reactive state, computed values, functions, और lifecycle hooks declare करते हैं, फिर template को expose करने वाली चीज़ों का एक object return करते हैं।

यह props और emit, slots, और attrs वाला एक context receive करता है। setup के अंदर कोई this नहीं है।

Note: single-file components में script setup syntax values manually return करने की ज़रूरत हटा देता है।

उदाहरण: setup()

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">
  <p>{{ greeting }} ({{ shout }})</p>
  <button @click="setName('Grace')">Rename</button>
</div>
<script>
  Vue.createApp({
    setup() {
      const name = Vue.ref("Ada");
      const greeting = Vue.computed(() => "Hello, " + name.value);
      const shout = Vue.computed(() => greeting.value.toUpperCase());
      const setName = (n) => { name.value = n; };
      return { greeting, shout, setName };
    },
  }).mount("#app");
  document.querySelector("button").click();
  Vue.nextTick(() => console.log(document.querySelector("p").textContent));
</script>
</body>
</html>

<!-- Output:
Rendered: Hello, Grace (HELLO, GRACE)Rename
console: Hello, Grace (HELLO, 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. setup के अंदर this इस्तेमाल करना
  2. values return करना भूल जाना
  3. props destructure करना और reactivity खोना
चैप्टर सारांश
  • setup component बनने से पहले चलता है
  • template को जो चाहिए वह return करें
  • यह props और context receive करता है
  • setup के अंदर कोई this नहीं
🔒

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.