Prop का Validation
Prop validation एक component को हर prop के लिए type, requirement, और rules declare करने देता है, development में warnings के साथ।
In this page:
Syntax
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
<!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. #}
आम गलतियां
- security के लिए validation पर depend करना
- defaults की तरह सीधे arrays या objects इस्तेमाल करना
- 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: