Description
I have read a number of discussions on this and think it's worthwhile to raise this as an enhancement.
The following esults in each element rendering as an <li>
with appropriate list styling but acting like a link. The problem is that if one of the links is to an external site it fails.
<template>
<nav class="navs">
<ul class="nav">
<!-- -->
<router-link
class="nav__item nav__link"
tag="li"
active-class="-active"
:to="nav.link"
:key="nav.name"
exact
v-for="nav in navs">
{{ nav.name }}
</router-link>
</ul>
</nav>
</template>
It's possible to convolute the logic with something like the following. It requires directly inserting the <a>
elements but works given minor changes to CSS or always inserting links inside <li>
elements (even though if there are no external links it can be coded using <router-link tag="li" ...>
).
<ul>
<li v-for="nav in navs">
<a v-if="nav.external" class="nav__item nav__link" :href="nav.link">{{ nav.name }}</a>
<router-link v-else
class="nav__item nav__link"
active-class="-active"
:to="nav.link"
:key="nav.name"
exact
>{{ nav.name }}</router-link>
</li>
</ul>
I previously tried just inserting external URLs into the <router-link>
elements and handling them in router.beforeEach()
. It's possible to apply some heuristic checks to see if the URL is external and set window.location.href
if it is. But the problem I ran into then is that using the browser back button always resulted in an error because the history is stored as localhost:8080/http:/google.com
(when testing with "http://google.com" as the external link).
It seems that that programmatically building lists of links is a common problem and that there should be a straightforward solution. Two solutions that would help me are 1) allowing the "external" prop on <router-link>
elements that correctly stores history so the back button works or 2) provide some way in router.beforeEach()
to prevent storing the unusable history entry. I think the first, or some variation where the externality of a link specified in the element, is the most straightforward.
I guess another solution is a strong recommendation in documentation on how to handle this seemingly common situation.
Thanks for considering it.