Vue Tip: Create Custom v-model Modifier
v-model
has some built-in modifiers like .lazy
, .number
and .trim
. But sometimes, you might need to add your custom modifier.
In this simple demo, I want to create a custom modifier called no-underscore
that removes all underscores _
from an input:
Inside our component we can access the modifier via the modelModifiers
prop. We manipulate the value if an input
event is fired and the modifier is available:
If your v-model
binding includes both modifiers and argument then the generated prop name will be arg + "Modifiers"
:
Demo for this code is available at Vue SFC Playground.
If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Vue Tip: Query Inner Elements in Third-Party Components
In some cases, we have to deal with third-party Vue components where we cannot put a ref on inner HTML elements to access them in our Vue code.
Vue Tip: Use Lazy v-model to Sync State After Change Events
By default, v-model syncs with the state of the Vue instance on every input event. The .lazy modifier syncs after change events.