Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activate method on router link click in Vue

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?

like image 207
A.J Avatar asked Sep 07 '18 21:09

A.J


People also ask

How do I redirect a URL in Vue?

Suppose we have a /contact route in our vue app, when a user visits the /contact page we need to redirect them to an external url https://www.google.com/contact/ instead of the same domain redirect. To redirect to an external url in Vue, we can use the window. location. href property.

Can Vue router open a link in a new tab?

to open a Vue Router link in a new tab, we can call the $router. resolve method to get the full URL from the route name, path, parameter and query values. Then we can use window. open to open the URL in a new tab.


1 Answers

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

like image 85
tony19 Avatar answered Sep 18 '22 05:09

tony19