Computer scienceFrontendVue.jsVue 3 SyntaxVue Directives

v-on

3 minutes read

Handling events is fundamental to creating web applications when you need to listen to user interactions and respond dynamically. v-on is one of Vue's directives designed to make event handling a breeze. In this topic, you will understand what v-on is all about, how to use it effectively, and where it comes in handy.

What is v-on?

v-on is a directive that binds event listeners to specific elements in your Vue templates. It allows you to respond to user interactions, such as clicks, inputs, or key presses. With v-on, you can execute methods, trigger functions, or change data properties when these events occur.

<template>
  <button v-on:click="sayHello">Click me!</button>
</template>

<script>
export default {
  setup() {
    const sayHello = () => {
      alert('Hello, Vue!');
    };

    return {
      sayHello
    };
  },
};
</script>

In this example, the v-on:click directive tells Vue to listen for a click event on the button element and call the sayHello method when it happens.

Example of v-on directive

Syntax and usage

Now, let's break down the syntax and usage of v-on. It's all about attaching an event listener to an element. Here's what it looks like:

<element v-on:eventName="handler">
  • element: the HTML element you want to listen to for an event.

  • eventName: the name of the event you wish to capture (e.g., click, input, submit).

  • handler: the function or method to be executed when the event occurs.

Here's a practical example:

<template>
  <input type="text" v-on:input="updateText" />
  <p>{{ message }}</p>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const message = ref('');

    const updateText = (event) => {
      message.value = event.target.value;
    };

    return {
      message,
      updateText
    };
  },
};
</script>

In this case, v-on:input listens for events on the text input field and calls the updateText method, which updates the message data property with the user's input.

You can also use inline JavaScript expressions as event handlers. For example:

<button v-on:click="count++">Increment</button>

In this case, every time the button is clicked, the count variable in the Vue component will be incremented.

Shorthand syntax

Vue knows that you don't want to type v-on: every time you handle an event. So, it provides a shorthand syntax:

<element @eventName="handler"> 
  • element: the HTML element you want to listen to for an event.

  • eventName: the name of the event you wish to capture (e.g., click, input, submit).

  • handler: the function or method to be executed when the event occurs.

This is functionally equivalent to the full syntax but makes your code cleaner and more readable. Here's another example using the shorthand syntax:

<template>
  <div @mouseover="changeColor" :style="{ backgroundColor: color }">Hover over me</div>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const color = ref('red');

    const changeColor = () => {
      color.value = color.value === 'red' ? 'blue' : 'red';
    };

    return {
      color,
      changeColor
    };
  },
};
</script>

Example of changeColor method

In this example, when the mouse pointer is over the div, the changeColor method will be invoked, changing the background color of the div. The :style directive is used to bind inline styles to an element.

Use cases for v-on

Now that you've got the basics covered, let's explore some common use cases for v-on.

  • Button clicks

<template>
  <button @click="toggleVisibility">
    {{ isVisible.value ? 'Hide' : 'Show' }} Details
  </button>
  <div v-if="isVisible.value">
    <p>Some details...</p>
  </div>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const isVisible = ref(false);

    const toggleVisibility = () => {
      isVisible.value = !isVisible.value;
    };

    return {
      isVisible,
      toggleVisibility
    };
  },
};
</script>

In this example, we're using v-on to listen for the click event on the button.

Initially, isVisible is false, so the button says "Show Details" and the div is not rendered.

Example of case for the button

When you click the button, toggleVisibility is called, which sets isVisible to true. The button's text changes to "Hide Details", and the div is rendered with the text "Some details...".

Example of case for the button-2

If you click the button again, toggleVisibility is called again, which sets isVisible back to false. The button's text changes back to "Show Details", and the div is removed from the DOM.

  • Form submission

<form @submit.prevent="submitForm">
   <!-- Form fields here -->
   <button type="submit">Submit</button> 
</form>

v-on is essential for handling form submissions. In this example, @submit.prevent prevents the default form submission behavior (which would cause the page to refresh) and calls the submitForm method instead.

Modifiers are postfixes denoted by a dot, used with Vue.js directives like v-on. They dictate particular behaviors for the directive. In the form submission example, we used .prevent with v-on, calling event.preventDefault(). This stops the form from refreshing the page upon submission.

  • Keyboard events

You can listen to keyboard events like keydown, keyup, or keypress using v-on. This allows you to create interactive and responsive applications that respond to user input.

<template>
  <input type="text" @keydown="handleKeydown">
</template>

<script>
export default {
  setup() {
    const handleKeydown = (event) => {
      console.log(`Key pressed: ${event.key}`);
    };

    return {
      handleKeydown
    };
  },
};
</script>

In this example, we're using v-on to listen for a keydown event on the input field. When a key is pressed, the handleKeydown method is called, which logs the pressed key.

Example of keyboard vent

Conclusion

In a nutshell, v-on is your go-to Vue directive for event handling. It allows you to listen to user interactions, execute methods, and create dynamic, responsive web applications. Remember the basic syntax, explore the shorthand, and use it for common scenarios like button clicks, form submissions, and keyboard events. With v-on, you're well on your way to creating interactive Vue.js applications that users will love!

How did you like the theory?
Report a typo