Vue.js 2.0 router link in a div component
Well, router-link
has a tag
prop. You're looking for this:
<router-link to="home" tag="div">Home</router-link>
The Vue Way
If you want <router-link>
to render as another tag, in your case div
, you can use tag prop to specify which tag to render to, and it will still listen to click events for navigation.
<router-link to="home" tag="div">Home</router-link>
You can also do this via one of pure HTML ways:
Way 1
<a href="/home">
<div>
Home
</div>
</a>
Way 2
<div style="cursor: pointer;" onclick="window.location='/home';">
Home
</div>
You can also modify second way in vue way as following:
<div style="cursor: pointer;" @click="redirectToHome">
Home
</div>
where you can define redirectToHome
method as following:
methods: {
redirectToHome () {
this.$router.push(
{
path: '/home',
}
)
},
Vue.js 3
Disclaimer: the question is about Vue.js 2. I saw that.
tag
attribute is no more
Instead, do a v-slot
such as:
<router-link to="/about" custom v-slot="{ navigate }">
<div role="link" @click="navigate">test</div>
</router-link>
custom
prevents the creation of ana
elementnavigate
is the function provided for thediv
, to activate navigationrole="link"
is accessibility stuff (you could omit it), but can also be used for CSS'ing the hand mouse cursor
CSS:
[role="link"]:hover {
cursor: pointer;
}
One could also just let the a
remain, since browsers are now better at dealing with a display:block
a
, but that's another story.