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:
1<template>
2 <Comp v-model.no-underscore="text" />
3</template>
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:
1<script setup>
2const props = defineProps({
3 modelValue: String,
4 modelModifiers: { default: () => ({}) },
5})
6
7const emit = defineEmits(['update:modelValue'])
8
9function emitValue(e) {
10 let value = e.target.value
11 if (props.modelModifiers['no-underscore']) {
12 // replace all underscores in a string
13 value = value.replace(/_/g, '')
14 }
15 emit('update:modelValue', value)
16}
17</script>
18
19<template>
20 <input type="text" :value="modelValue" @input="emitValue" />
21</template>
If your v-model
binding includes both modifiers and argument then the generated prop name will be arg + "Modifiers"
:
1<template>
2 <Comp v-model:name.no-underscore="text" />
3</template>
4
5<script setup>
6const props = defineProps(['name', 'nameModifiers'])
7defineEmits(['update:name'])
8</script>
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.