Mokkapps Logo

Vue Tip: Create Custom v-model Modifier

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
May 11, 2022
1 Minuten Lesezeit
|
- Ansichten

v-model has some built-in modifiers like .lazy, .number and .trim. But in some cases, you might need to add your own 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 tip, follow me on Twitter to get notified about new tips, blog posts, and more content from me.

Alternatively (or additionally), you can also subscribe to my newsletter.

Sie haben einen Fehler in diesem Artikel gefunden? Sie möchten gerne etwas klarstellen, aktualisieren oder hinzufügen?

Alle meine Artikel können auf Github editiert werden. Jeder Fix ist willkommen, egal wie klein er sein mag!

Ändern auf Github