使用 "v-on:" 指令将事件侦听器添加到 <router-link> 组件 - VueJS

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

我正在尝试将自定义处理程序 InlineButtonClickHandler 添加到 <router-link> 组件的 click 事件,以便我可以发出自定义 appSidebarInlineButtonClick 事件。

但是,我的代码不起作用。我究竟做错了什么?

<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>

您需要添加.native modifier

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

这将监听 router-link 组件根元素的原生点击事件。

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

也许你可以试试这个。

对于 vue 3 和 vue router 4,根据 this 删除了 @eventtag 道具,您可以使用 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>