Skip to main content

What does a modifier do in a directive?

A directive modifier is a suffix after a dot (.) that refines or changes the behavior of a directive. It does not change the directive itself, it adds extra functionality to it.

Modifiers exist on built-in directives (v-on, v-bind, v-model) and can also be used on custom directives.


What does a modifier look like?

javascript
v-on:click.prevent v-model.lazy v-bind:class.prop

Modifiers always come after the directive and its argument:

javascript
directive:argument.modifier1.modifier2

Examples of modifiers on standard directives

v-on (event handlers)

javascript
<button @click.stop="doSomething">Stop propagation</button> <button @click.prevent="submit">Prevent the browser's default behavior</button> <button @click.once="init">Fires once</button>

Main v-on modifiers:

  • .stop - calls event.stopPropagation()
  • .prevent - calls event.preventDefault()
  • .capture - listen for the event during the capture phase
  • .self - fires only if the click is on the element itself
  • .once - the handler fires only once
  • .passive - passive: true for performance

v-model

javascript
<input v-model.lazy="name">

Modifiers:

  • .lazy - update the value on change instead of input
  • .trim - automatically trim whitespace
  • .number - cast to a number

v-bind

javascript
<div :class.prop="myClasses"></div>
  • .prop - bind as a DOM property instead of an attribute
  • .camel - convert the attribute name to camelCase

Modifiers in custom directives

You can use modifiers yourself too:

javascript
<div v-focus.delay="300"></div>

Inside the directive, you can read them:

javascript
app.directive('focus', { mounted(el, binding) { if (binding.modifiers.delay) { setTimeout(() => el.focus(), binding.value || 0); } else { el.focus(); } } });

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.