← Back to Vue.js Course | Chapter 6: Component Communication | Lesson 7 of 7

Default Props का उपयोग

Optional props की एक default value हो सकती है जो तब इस्तेमाल होती है जब parent एक pass न करे।

In this page:

  1. Default Props
Syntax
markup
props: {
  propName: {
    type: Type,
    default: value
  },
  listProp: {
    type: Array,
    default: () => []
  }
}

Default Props

एक prop को इसकी object definition में एक default दें। Objects और arrays के लिए, default एक factory function होना चाहिए ताकि हर instance को इसकी अपनी copy मिले। छोड़े गए Boolean props default से false होते हैं, और बिना किसी value के pass किया एक prop true count होता है।

Note: Default arrays और objects return करने के लिए एक function इस्तेमाल करें।

उदाहरण: Default props

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">
  <greeting-line></greeting-line>
  <greeting-line name="Ada" :tags="['math']" loud></greeting-line>
</div>
<script>
  const app = Vue.createApp({});
  app.component("greeting-line", {
    props: {
      name: { type: String, default: "friend" },
      tags: { type: Array, default: () => ["none"] },
      loud: Boolean,
    },
    template: "<p>{{ loud ? 'HELLO' : 'Hello' }}, {{ name }} [{{ tags.join(',') }}]</p>",
  });
  app.mount("#app");
</script>
</body>
</html>

<!-- Output:
Rendered: Hello, friend [none]HELLO, Ada [math]
-->
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. एक array default की तरह एक shared object इस्तेमाल करना
  2. यह उम्मीद करना कि undefined एक default को override करेगा
  3. यह भूल जाना कि booleans default से false हैं
चैप्टर सारांश
  • default एक fallback supply करता है
  • Object और array defaults functions इस्तेमाल करते हैं
  • Absent Boolean props false हैं
  • undefined default trigger करता है
🔒

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.