·
1 min read

Vue Tip: Create Custom v-model Modifier

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:

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:

I will never share any of your personal data. You can unsubscribe at any time.