Add event listener to <router-link> component using "v-on:" directive - VueJS

Vuejs2vue.jsVue Router

Vuejs2 Problem Overview


I'm attempting to add a custom handler InlineButtonClickHandler to a <router-link> component's click event, so that I can emit a custom appSidebarInlineButtonClick event.

But, my code isn't working. What am I doing wrong?

<template>
   <router-link :to="to" @click="InlineButtonClickHandler">
     {{ name }}
   </router-link>
</template>

<script type="text/babel">
export default {
  props: {
    to: { type: Object, required: true },
    name: { type: String, required: true }
  },
  methods: {
    InlineButtonClickHandler(event) {
      this.$emit('appSidebarInlineButtonClick');
    }
  }
} 
</script>

Vuejs2 Solutions


Solution 1 - Vuejs2

You need to add the .native modifier:

<router-link
    :to="to"
    @click.native="InlineButtonClickHandler"
>
    {{name}}
</router-link>

This will listen to the native click event of the root element of the router-link component.

Solution 2 - Vuejs2

<router-link:to="to">
    <span @click="InlineButtonClickHandler">{{name}}</span>
</router-link>

Maybe you can try this.

Solution 3 - Vuejs2

With vue 3 and vue router 4 the @event and tag prop are removed according to this and instead of that you could use v-slot:

const Home = {
  template: '<div>Home</div>'
}
const About = {
  template: '<div>About</div>'
}
let routes = [{
  path: '/',
  component: Home
}, {
  path: '/about',
  component: About
}, ]

const router = VueRouter.createRouter({
  history: VueRouter.createWebHashHistory(),
  routes,
})


const app = Vue.createApp({
  methods: {
    test() {
      console.log("test")
    }
  }
})

app.use(router)

app.mount('#app')

<script src="https://unpkg.com/vue@3"></script>
<script src="https://unpkg.com/vue-router@4"></script>

<div id="app">
  <h1>Hello App!</h1>
  <p>

    <router-link to="/" v-slot="{navigate}">
      <span @click="test" role="link">Go to Home</span>
    </router-link>
    <br/>
    <router-link to="/about">Go to About</router-link>
  </p>

  <router-view></router-view>
</div>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEvgeniy MiroshnichenkoView Question on Stackoverflow
Solution 1 - Vuejs2thanksdView Answer on Stackoverflow
Solution 2 - Vuejs2许浩东View Answer on Stackoverflow
Solution 3 - Vuejs2Boussadjra BrahimView Answer on Stackoverflow