Javascript is required
Mokkapps LogoMichael Hoffmann

Vue Tip: Create Custom v-model Modifier

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
Michael Hoffmann
May 11, 2022
1 min read
|
117 views
v-model
Vue Tip: Create Custom v-model Modifier Image

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:

<Comp v-model.no-underscore="text" />

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:

<script setup>const props = defineProps({  modelValue: String,  modelModifiers: { default: () => ({}) },})const emit = defineEmits(['update:modelValue'])function emitValue(e) {  let value = e.target.value  if (props.modelModifiers['no-underscore']) {    value = value.replace('_', '')  }  emit('update:modelValue', value)}</script><template>  <input type="text" :value="modelValue" @input="emitValue" /></template>

If your v-model binding includes both modifiers and argument then the generated prop name will be arg + "Modifiers":

<template>  <Comp v-model:name.no-underscore="text" /></template><script setup>const props = defineProps(['name', 'nameModifiers'])defineEmits(['update:name'])</script>

Demo for this code is available at Vue SFC Playground


If you liked this Vue tip, follow me on Twitter to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue newsletter.