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

家住魔仙堡 提交于 2019-11-27 15:35:23

问题


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>

回答1:


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.




回答2:


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

Maybe you can try this.




回答3:


a nice solution would be:

<a v-link='{name: "home"}' v-on:click.capture='InlineButtonClickHandler'>Home</a>



来源:https://stackoverflow.com/questions/42091805/add-event-listener-to-router-link-component-using-v-on-directive-vuejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!