Vue router conditional redirect?

Viewed 3911

I am trying to build a simple Vue app where the router links would be based on the data received from the server, the data is something like this.

id: 1
path: "category_image/About.jpg"
slug: "about"
subtitle: null
title: "About Us"
url: "http://archeoportal.loc/page/about"

Now what i am trying to achieve is dynamic router-link elements which would use window.location.href if the url field is not null otherwise i want it to be just a router link. Currently what I've done doesn't work, it keep throws errors like TypeError: Cannot read property 'redirect' of undefined. Here's what's my Vue file looks like

<router-link
  :to="this.redirect(category.url !== null ? category.url : category.slug, category.url !== null ? true : false)"
  class="grid-item"
  v-bind:key="category.id"
  v-for="category in this.categories"
>
    <div class="category-title py-4">
      <h2>{{ category.title }}</h2>
      <p>{{ category.description }}</p>
    </div>
  <img :src="`/storage/${category.path}`" />
</router-link>

as you can see i am using a custom method for that which is in my methods and goes something like this

methods:{
  redirect(url, window){
    if(window == true){
      window.location.href = url;
    }else{
      this.router.push('url');
    }
  }
}

But my Vue app crashed and doesn't display anything, is there any way i can achieve this?

1 Answers

to in router-link should only take the name of the link.

You don't need a custom method to do this. A better way to do this would be using <a> tags in case of url redirection:

<div 
  v-for="category in this.categories"
  :key="category.id"
>
  <a 
    v-if="category.url"
    :href="category.url"
  >
    <div class="category-title py-4">
      <h2>{{ category.title }}</h2>
      <p>{{ category.description }}</p>
    </div>
  </a>
  <router-link
    v-else
    :to="`/${category.slug}`"
    class="grid-item"
  >
    <div class="category-title py-4">
      <h2>{{ category.title }}</h2>
      <p>{{ category.description }}</p>
    </div>
    <img :src="`/storage/${category.path}`" />
  </router-link>
</div>

If you want to keep the implementation using a separate function, again use <a> instead of router-link as follows:

<a
  @click="redirect(category.url !== null ? category.url : category.slug, category.url !== null)"
  ...
>
methods: {
  redirect(url, isRedirect) {           
    if (isRedirect === true) {
      window.open(url);
    } else {
      this.router.push(`/${url}`);
    }
  }
}
Related