Is it possible to conditionally redirect using Vue router?

I am in the process of creating a straightforward Vue application where the router links will be determined by the data retrieved from the server. The format of the data looks something like this:

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

My goal is to generate dynamic router-link elements that use window.location.href if the url field is not empty, otherwise I want it to function as just a regular router link. However, my current implementation is encountering errors such as

TypeError: Cannot read property 'redirect' of undefined
. Here's what my Vue file resembles:

<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 observe, I utilize a custom method for this purpose that resides in my methods and functions in the following manner:

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

Unfortunately, my Vue application crashes and nothing gets displayed. Is there an alternate approach to achieve this functionality?

Answer №1

Make sure the in router-link only includes the link name.

No custom method is necessary for this task. A more efficient approach would be to use <a> tags for 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 prefer using a separate function, opt for <a> over router-link as shown below:

<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}`);
    }
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I retrieve the /api/auth/me resource serverside using the NextJS AppRouter?

I am looking to implement app router in my Next.js project and have encountered an issue. In order for my app to function properly, I need to make a call to /api/auth/me which will return either a user object or null if the user is not logged in. To achiev ...

The URL not functioning properly after including the .active class with JQuery

This website is built on the Shopify platform. To highlight an active link in a subcategory list, I am using JQuery and CSS to add the .active class to the element. However, after adding the JQuery code, the link element is not functioning properly and d ...

directive in Angular ordering

After exploring this link, my understanding deepened: http://plnkr.co/edit/k5fHMU?p=preview Upon analyzing the code snippet provided in the link above, I noticed that the Angular app consists of both a controller and a directive. However, there seems to ...

Issue regarding navigation using nuxt-links to pages with hashtags/anchors

When it comes to my website navigation, I rely on nuxt-links a lot. Most of these links direct users to specific sections within the home page using hashes like: <nuxt-link v-else class="text-link" :to="localePath('index') + #hash" > ...

Using Jest functions as object properties results in undefined behavior

I am faced with a challenge in my class where I need to mock an object along with its properties intercept(context: ExecutionContext) { const response = contect.switchToHttp().getResponse() // the chain that needs to be mocked if (response.headersSent ...

Why is my VueJS 2.0 deployment to a sub-folder resulting in a blank page?

I've been attempting to launch my Vue2 web application in a subdirectory on my domain, but I'm encountering a blank page. I've experimented with various solutions like adjusting the config/index.js file to correspond with the path on my live ...

How should I proceed if a TypeScript definition file that I am relying on is lacking a specific definition?

I have encountered an issue while using the React type definitions for my project. The focus method is missing on elements in the array returned by the refs property, which prevents me from getting a specific example to work. The compiler error states: pro ...

Developing a personalized language setting in Nuxt.js for internationalization

I'm facing an issue with my application where I am struggling to figure out how to create a custom locale. For example, I have routes like /hello and /ja/hello, where the first route is for the default English language and the second one is for Japane ...

Link the ngModel input to an object within an ngFor iteration

Looking to create a dynamic form using an array that includes FieldLabel and DataModel references. I want to use the DataModel as an object reference, so when the user updates an input field, the referenced model is updated. I have searched extensively bu ...

Experience a seamless front/back DIV transition with a mouseover effect similar to the ones on USAT

Recently, I was tasked with creating a mouseover transition effect for a div similar to the one used on USAToday's website. The structure of the boxes on the site includes: <div class="asset"> <div class="front">'image and some t ...

sanitizing user input in an AngularJS application

I created a feature in angular using ng-repeat <ul class="messages"> <li ng-repeat="e in enquiries"> <img src="/img/avatar.jpg" alt=""> <div> ...

Check to see if the event handler is triggered and the promises are executed in sequence (syncronously)

I have a Vue button click handler that, depending on the arguments it receives, can do the following: execute request A only execute request B only execute request A and then request B sequentially (request B is only called if request A completes successf ...

The entry '0-0' already exists for the key 'local_part', please enter a unique value

Creating a simple API to handle GET, POST, DELETE, and UPDATE requests. The GET method is functioning correctly, but encountering an issue with the POST method. When attempting to post data, an error is being encountered: error: Error: ER_DUP_ENTRY: ...

Retrieve outcome from successful AJAX post and update HTML using globalEval

I have a function in JQuery that asynchronously posts data function post_data_async_globalEval(post_url, post_data, globaleval) { $.ajax({ type: 'POST', url: post_url, data: post_data, dataType: 'html', async: true, ...

Vue template compilation issue: 'undefined' properties cannot be read (referencing '_c')

Currently, I am in the process of integrating a customized tool into an existing Laravel application by utilizing Laravel Nova for the administrative panel. However, the automatically generated tool created with "php artisan nova:tool vendor/name" does not ...

Empower the user with the ability to interact through touch on dynamically

I am trying to make a div touchable and draggable. I have dynamically created 1 to 10 divs within another div. Currently, these divs can only be dragged using the mouse or cursor. However, I want to enable dragging through touch as well. Can anyone provi ...

Altering the context of Javascript script execution

I needed to switch the JavaScript execution context from the parent window to the child window. I was able to successfully load my script objects and functions into the child window context, however, I encountered difficulty in making third party libraries ...

Discovering the magic of nesting maps in React-Native without the need for

I am currently developing a react-native app that retrieves its data through an API. I am working on implementing a new feature where the information is grouped by date. The JSON data structure sent by the API looks like this: { "channel_count" ...

Skip a single test from a suite in Firefox using Protractor automation framework

I have a collection of tests in my tests folder, all named with the convention ending in spec.js. By using the */spec.js option in the Config file, I am able to run all tests seamlessly. However, I encountered an issue where I needed to skip running a spe ...

Creating an Angular JS controller that utilizes a filter for a JSON array of objects

I have the following JSON data and I'm trying to determine the number of objects with Status: 1 in the JSON. The approach I've taken so far is not working. I understand that ng-filter should only be applied to Arrays, but I'm struggling to ...