javascript / expert
Snippet
Intercepting v-model with defineModel
Vue 3.4 introduced a powerful way to handle v-model modifiers. By destructuring 'defineModel', you can access custom modifiers and use the 'set' transformer to intercept and modify the data before it flows back to the parent.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
// In a Child Componentconst [modelValue, modifiers] = defineModel({set(value) {if (modifiers.capitalize) {return value.charAt(0).toUpperCase() + value.slice(1);}return value;}});// In Parent// <MyInput v-model.capitalize="name" />
vue
Breakdown
1
if (modifiers.capitalize)
Checks if the '.capitalize' modifier was used on the parent call.
2
set(value) { ... }
A transformer function that sanitizes the outgoing value.