Home » vue » Vue prevent on component link not working

Vue prevent on component link not working

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have
component tag:

<template>
    <a href="url">hi</a>
</template>

On other page i show tag and want call my method on mouseClick

<tag @click.prevent="myFunction"></tag>

But i get redirect to url. Prevent modificator dont work. How fix this ?

Update:

Equal question but if change html ‘A’ to vue router link

<template>
   <router-link :to="{ name: 'OtherPage'}"></router-link>
</template>
Answers:

Binding Native Events to Components

There may be times when you want to listen directly to a native event on the root element of a component. In these cases, you can use the .native modifier for v-on:

Just add .native modifier to your component to get the native behavior you’r expecting.

<tag @click.native.prevent="myFunction"></tag>

const Tag = Vue.component('Tag', {
  template: '<a href="http://url.com">My Link</a>',
  
})

new Vue({
  el: '#app',
  components:{
    Tag
  },
  methods:{
    myFunction(){
        alert(`Won't redirect you`)
    }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <tag @click.native.prevent="myFunction"/>
</div>

###

You code is not working because you add a listener on tag component not a element.

Using the $listeners property, you can forward all event listeners on the component to a specific child element with v-on="$listeners"

Read more.

Example code:

<div id='app'>
  <tag url='/abc' text='Click Me' @click.prevent='myFunction'></tag>
</div>

and

<template>
  <a :href='url' v-on='$listeners'>{{ text }}</a>
</template>

JSFiddle