Vue.js Link Click Handling Example

AuthorSumit Dey Sarkar

Pubish Date09 Mar 2024

categoryVue JS

In this tutorial, we will see Vue.js link click handling example.

Vue.js Link Click Handling Example

Handling click events with Vue

If you want to prevent the default behavior of a link click in Vue.js and also capture some information associated with that link (like an object), you can use the @click.prevent event handler to prevent the default action and then call a method that handles the click event while passing the relevant object. Here's an example:

Assuming you have a link in your template:

<template>
  <div>
    <a href="#" @click.prevent="handleLinkClick(someObject)">Click me</a>
  </div>
</template>

In your Vue component:

<script>
export default {
  data() {
    return {
      someObject: { /* Your object data here */ }
    };
  },
  methods: {
    handleLinkClick(obj) {
      // Perform any actions you need with the object
      console.log('Object clicked:', obj);
      
      // If you want to navigate to the link's href after handling the click
      // window.location.href = event.currentTarget.href;
    }
  }
}
</script>

In this example:

  • @click.prevent prevents the default behavior of the link.
  • The handleLinkClick method is called when the link is clicked, and it takes the someObject as an argument.
  • You can then perform any actions you need with the object in the handleLinkClick method.
Comments 0

Leave a comment