Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional <router-link> in Vue.js dependant on prop value?

Hopefully this is a rather simple question / answer, but I can't find much info in the docs.

Is there a way to enable or disable the anchor generated by <router-link> dependent on whether a prop is passed in or not?

<router-link class="Card__link" :to="{ name: 'Property', params: { id: id }}">
  <h1 class="Card__title">{{ title }}</h1>
  <p class="Card__description">{{ description }}</p>
</router-link>

If there's no id passed to this component, I'd like to disable any link being generated.

Is there a way to do this without doubling up the content into a v-if?

Thanks!

like image 578
Michael Giovanni Pumo Avatar asked Jun 29 '17 15:06

Michael Giovanni Pumo


1 Answers

If you need to use it often, consider this:

Create new component

<template>
  <router-link
    v-if="!disabled"
    v-bind="$attrs"
  >
    <slot/>
  </router-link>

  <span
    v-else
    v-bind="$attrs"
  >
    <slot/>
  </span>
</template>

<script>
export default {
  name: 'optional-router-link',

  props: {
    params: Object,
    disabled: {
      type: Boolean,
      default: false,
    },
  },
};
</script>

Optional, register globally:

Vue.component('optional-router-link', OptionalRouterLink);

Use it as follows:

<optional-router-link
  :disabled="isDisabled"
  :to="whatever"
>
    My link
</optional-router-link>
like image 54
Joey van Breukelen Avatar answered Oct 06 '22 18:10

Joey van Breukelen