How to Use a Button as a Link in Vue
To use a button as a link in Vue, you can wrap the button in an anchor (<a>
) element. Clicking a link button makes the browser navigate to the specified URL.
<template>
<div>
<a href="/posts">
<button>Posts</button>
</a>
</div>
</template>
Use button as Vue Router link
When working with Vue Router, you can make a button serve as a router link using the navigate
function provided by the router-link
default slot.
<template>
<div>
<router-link
to="/posts"
custom
v-slot="{ navigate }"
>
<button
@click="navigate"
role="link"
>
Posts
</button>
</router-link>
</div>
</template>
/posts
route without refreshing the page.We use navigate
as a handler for the click
event, so it is called when the button is clicked, making the browser navigate to the specified route without refreshing the page.
The above method only works for Vue 3.x though. If working with Vue 2.x, you can use a button as a router link by setting the tag
prop to the name of the button component, and setting the to
prop to the specific route.
<template>
<div>
<router-link to="/posts" tag="button">Posts</router-link>
</div>
</template>
The $router.push() method
Alternatively, we can use a button as a Vue router link by calling the push()
method on the $router
variable made available by Vue Router.
<template>
<div>
<button @click="$router.push('/posts')">Posts</button>
</div>
</template>
The $router
variable represents the router instance, and can be used for programmatic navigation.
Use Vuetify button as link
When working with the Vuetify framework, we can use the button component as a link by setting the v-btn
href
prop.
<template>
<div>
<v-btn
href="/posts"
color="primary"
dark
>
Posts
</v-btn>
</div>
</template>
Use Vuetify button as Vue Router link
When using Vue Router with Vuetify, we can use the button component as a router link by setting the v-btn to
prop.
<template>
<div>
<v-btn
to="/posts"
color="primary"
dark
>
Posts
</v-btn>
</div>
</template>
Use Vue Bootstrap button as link
If you're working with the Vue Bootstrap framework, you can use the href
to turn the button component into a link.
<template>
<div>
<b-button
href="/posts"
variant="primary"
>
Posts
</b-button>
</div>
</template>
Use Vue Bootstrap button as Vue Router link
We can set the b-button
to
prop to use the Vue Bootstrap button component as a Vue Router link.
<template>
<div>
<b-button
to="/posts"
variant="success"
>
Posts
</b-button>
</div>
</template>