← Back to Vue.js Course | Chapter 5: Forms | Lesson 5 of 6

Custom v-model का उपयोग

एक component एक modelValue prop accept करके और update:modelValue emit करके खुद v-model support कर सकता है।

In this page:

  1. Custom v-model
Syntax
markup
// child
props: ['modelValue'],
emits: ['update:modelValue'],
template: '<input :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)">'

// parent
<child-name v-model="property"></child-name>

Custom v-model

Vue 3 में एक component पर v-model एक modelValue prop pass करता है और update:modelValue सुनता है। v-model:title जैसे Named models इसकी बजाय title और update:title इस्तेमाल करते हैं, और एक component कई accept कर सकता है। Modifiers modelModifiers में आते हैं।

Note: एक component पर v-model under the hood बस एक prop plus एक event है।

उदाहरण: Custom v-model

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">
  <star-rating v-model="rating"></star-rating>
  <p>Rating is {{ rating }}</p>
</div>
<script>
  const app = Vue.createApp({ data() { return { rating: 1 }; } });
  app.component("star-rating", {
    props: ["modelValue"],
    emits: ["update:modelValue"],
    template: '<span><button v-for="n in 5" :key="n" @click="$emit(\'update:modelValue\', n)">{{ n <= modelValue ? "★" : "☆" }}</button></span>',
  });
  app.mount("#app");
  document.querySelectorAll("button")[3].click();
  Vue.nextTick(() => console.log(document.querySelector("p").textContent));
</script>
</body>
</html>

<!-- Output:
Rendered: ★★★★☆Rating is 4
console: Rating is 4
-->
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. Vue 2 के value और input names इस्तेमाल करना
  2. update event emit करना भूल जाना
  3. prop सीधे mutate करना
चैप्टर सारांश
  • modelValue prop और update:modelValue event इस्तेमाल होते हैं
  • Named models v-model:name इस्तेमाल करते हैं
  • कई v-models allowed हैं
  • Vue 2 के value और input की जगह लेता है
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 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.