Custom v-model
A component can support v-model itself by accepting a modelValue prop and emitting update:modelValue.
In this page:
Syntax
// 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
<!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
- Using the Vue 2 value and input names
- Forgetting to emit the update event
- 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: