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?
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.
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.
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
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>
's custom
prop 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>.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With