'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?
Solution 1:[1]
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>
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.
Apply
<router-link>'scustomprop to enable the default slot customization.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>.hrefb.
navigate(the method that performs the navigation to the route) to<a>.@click. Passnavigateand the$event(a special argument) to a method that runs the secondary method and then thenavigate()method with$eventas 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)
},
},
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
