12

I am working on account removal on a Chrome extension and I have the following button:

<button @click="remove" id="button_remove" class="btn btn-default" style="float: right;">Remove Account</button>

JS

methods:{
    remove(event){
       app.removeAccountData(url,apikey);
    }
},

I also have this router-link:

<router-link :to="{ name: 'RemovedWId', params: { accountid: chosenAccount.apikey}}" text="delete_account"><span class="glyphicon glyphicon-trash" aria-hidden="true" style="margin-top: 2px; cursor: pointer;"></span> Remove Account</router-link>

Is there a way to use the router-link with the JS function?

tony19
  • 125,647
  • 18
  • 229
  • 307
A.J
  • 1,140
  • 5
  • 23
  • 58

1 Answers1

26

Vue 2

With Vue Router 3, <router-link> is a component wrapper around <a>, so we'll need to use the .native modifier for it to properly receive the event:

<router-link @click.native="removeAccount" to="/remove">Remove</router-link>

demo 1

Vue 3

With Vue Router 4, <router-link> no longer passes its attributes and event handlers to its inner component, and Vue 3 no longer supports the .native event modifier. You'd have to apply the @click handler manually via <router-link>'s custom default slot.

  1. Apply <router-link>'s custom prop to enable the default slot customization.

  2. In the <router-link>'s default slot, add an <a> and bind the following slot props:

    a. href (the resolved URL to the route) to <a>.href

    b. navigate (the method that performs the navigation to the route) to <a>.@click. Pass navigate and the $event (a special argument) to a method that runs the secondary method and then the navigate() method with $event as the argument.

<router-link to="/remove" custom v-slot="{ href, navigate }">
  <a :href="href" @click="wrapNavigate(navigate, $event)">Remove</a>
</router-link>
export default {
  methods: {
    removeAccount() {
      // ...
    },
    wrapNavigate(navigate, event) {
      this.removeAccount()
      navigate(event)
    },
  },
}

demo 2

tony19
  • 125,647
  • 18
  • 229
  • 307
  • 1
    Another Vue2 caveat: Keep in mind the `@click.native` event may not consistently occur before-or-after the `router-link` click event (depending on browser ie Edge vs Firefox vs Chrome, etc). In my case I was trying to grab route data on the click handler, but route data would differ if route change had already occurred by the time my click logic ran. In the end, I had to leverage `vue-router`'s navguards and a custom global store. – Kalnode Apr 19 '22 at 16:06
  • Lots of relevant discussion on this here: https://github.com/vuejs/vue-router/issues/974 – Kalnode Apr 19 '22 at 16:07
  • 2
    This seems to work for Vue 3 and Vue Router 4 – dras Mar 22 '23 at 00:07
  • 2
    [demo](https://stackblitz.com/edit/vue3-click-handler-on-router-link-dzsbsc?file=src/App.vue) yolo – dras Mar 22 '23 at 00:14