Vuejs V-on and v-bind directives examples| Shorthand syntax

In this short tutorial, you will learn about the v-on and v-bind directives in Vue.js along with their shorthand syntax, illustrated with examples.

v-on directive in vuejs

The v-on directive in Vue.js adds dynamic behavior to HTML templates. It serves as the binding event handler for listening to JavaScript native events.

v-on attaches an event listener to an HTML element, allowing it to respond to specific events.

Here’s the syntax:

Syntax

<htmltag v-on:Events:modifier="Eventhandler"></htmltag>
<htmltag @:Events:modifier="Eventhandler"></htmltag>

Events can include click events, button clicks, or input keypress events, among others. Modifiers are used to modify event behavior, such as preventing page reloads.

For example, v-on:submit.prevent prevents the default form submission behavior.

Example:

Here’s the full syntax for handling events and event handlers.

As per the documentation, the Button click handler can be handled with different syntax.

v:on click, the handler button can be declared as follows

<button v-on:click="onSubmitEvent"></button>

This can be shortened using the @ syntax:

<button @click="onSubmitEvent"></button>

Both syntaxes achieve the same functionality.

Difference between @click and v-on:click Directive

  • Both serve the same purpose.
  • They differ only in syntax.

Both do the same thing, @click is a shorthand version of the v-on:click directive.

v-bind Directive in Vue.js

The v-bind directive in Vue.js is used to bind tag attributes dynamically.

Here’s the syntax:

<htmltag v-bind:attribute="" ></htmltag>
<htmltag :attribute=""></htmltag>

added v-bind attribute to HTML element. For example, binding Anchor with href attribute using long syntax.

<a v-bind:href="{{this.url}}"></a>

This can be shortened using the shorthand syntax.

<a :href="{{this.url}}"></a>