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

Custom v-model

A component can support v-model itself by accepting a modelValue prop and emitting update:modelValue.

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

In Vue 3 v-model on a component passes a modelValue prop and listens for update:modelValue. Named models such as v-model:title use title and update:title instead, and a component can accept several. Modifiers arrive in modelModifiers.

Note: v-model on a component is just a prop plus an event under the hood.

Example: 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
  1. Using the Vue 2 value and input names
  2. Forgetting to emit the update event
  3. Mutating the prop directly
Chapter Summary
  • modelValue prop plus update:modelValue event
  • Named models use v-model:name
  • Several v-models are allowed
  • Replaces Vue 2 value and 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.