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

Prop का Validation

Prop validation एक component को हर prop के लिए type, requirement, और rules declare करने देता है, development में warnings के साथ।

In this page:

  1. Prop Validation
Syntax
markup
props: {
  propName: {
    type: Type,
    required: true,
    default: value,
    validator(value) {
      return condition;
    }
  }
}

Prop Validation

type, required, और validator वाला props का object form इस्तेमाल करें। जब एक value match न हो Vue development builds में warn करता है। Types में String, Number, Boolean, Array, Object, Function, और custom classes शामिल हैं, और आप एक array से कई types allow कर सकते हैं।

Note: Validation warnings सिर्फ development builds में appear होते हैं।

उदाहरण: Prop validation

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">
  <level-badge :level="3" label="Gold"></level-badge>
  <level-badge level="oops" label="Bad"></level-badge>
</div>
<script>
  const app = Vue.createApp({});
  app.component("level-badge", {
    props: {
      level: { type: Number, required: true, validator: (v) => v >= 1 && v <= 5 },
      label: { type: String, required: true },
    },
    template: "<p>{{ label }}: level {{ level }}</p>",
  });
  app.config.warnHandler = (msg) => console.log("warning:", msg.split("\n")[0]);
  app.mount("#app");
</script>
</body>
</html>

<!-- Output:
Rendered: Gold: level 3Bad: level oops
console: warning: Invalid prop: type check failed for prop "level". Expected Number with value NaN, got String with value "oops".
-->
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. security के लिए validation पर depend करना
  2. defaults की तरह सीधे arrays या objects इस्तेमाल करना
  3. console में warnings ignore करना
चैप्टर सारांश
  • type, required, validator declare करें
  • Types types के arrays हो सकते हैं
  • Warnings development में appear होते हैं
  • Validation security नहीं है
🔒

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.