Vue-router: Allow null to be passed to router-link

Created on 8 May 2020  ·  3Comments  ·  Source: vuejs/vue-router

What problem does this feature solve?

If you want an <a> link not to behave as a link in html, you can remove the value of the href attribute. I tried to get the same behavior by setting <router-link :to="null"> but this gives an error that the to prop must be a string or an object. Null should be allowed as well, which would remove any href that might be present on the target element. This way we can have a generated link behave as a <a> with no href.

What does the proposed API look like?

<router-link :to="null">

All 3 comments

if you need to use a placeholder link, you can directly use that and branch between them with a v-if. You can extend RouterLink to have that behavior.

In practice, I would recommend using a role attribute instead of creating a placeholder link but I don't know all use cases of it either.

<a> tags have different behavior if href is present or not. An option to remove the href in the <a> that <router-link> generates would be very useful. Without it vue-router is stopping us from taking advantage of the full power of the underlying tag element.

Passing :to="null" was just one idea of how to give us access to this feature of the <a> tag.

Without this we'll have to use <a> instead of <router-link> and basically reimplement all the functionality of router-link just to get href not to be present. Your idea to have a v-if means duplicating the styles and text and listeners on the router-link on the "placeholder" link as you call it, adding more code and duplication to use a simple and useful feature that <a> tags provide in all browsers.

I use a solution that alters the tag used to render the link between <a> and <button> then I add a disabled property which helps with any repetition issues the v-if / v-else alternation approach can cause. Of course, this only works when dealing with links that look like a button and may not work well for textual links.

For textual links, you may be able to change the tag from <a> to <span> or something else with a conditional CSS class added to the <span> if you need to make it look more like the <a> using traditional Vue class binding techniques.

<router-link
  class="button is-circular is-primary is-pulled-left is-relative"
  :disabled="typeof previousUser === 'undefined'"
  :tag="typeof previousUser === 'undefined' ? 'button' : 'a'"
  :to="`/grade-activity/${activityId}/lti-user/${
    typeof previousUser !== 'undefined' ? previousUser.id : 0
  }?all=${!isViewingUngraded}`"
>
  <span class="icon">
    <font-awesome-icon icon="chevron-left" />
  </span>
</router-link>
Was this page helpful?
0 / 5 - 0 ratings