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

Blend the power of Node's CommonJS with the versatility of Typescript's ES modules

I currently have a Node.js v10 legacy application that was built using CommonJS modules (require). The entire codebase is written in JavaScript. However, I am considering upgrading the app and refactoring a specific part of it to use TypeScript modules ( ...

What is the recommended depth in the call stack to utilize the await keyword for an asynchronous function?

My knowledge of async functions in TypeScript/React is fairly basic. I have two API calls that need to be made, and I am using async functions to call them from my UI. It's crucial for these calls to have completed before rendering the component corre ...

Struggling to maintain preventDefault functionality while utilizing a submitHandler, causing the form to bypass and directly access the AJAX PHP

I'm having trouble keeping my AJAX call within the same page. Despite multiple attempts with preventDefault(), the form keeps getting submitted. Below is the complete code for a form with ID "#leadform" and a button with ID "#submitButton". $(docume ...

When using res.render to send results, redundant lines are displayed

I feel like I must be missing something really obvious, but for the life of me I cannot figure out what it is. All I want to do is list the documents in a MongoDB collection in a straightforward manner. I am working with nodejs, mongoose, and Jade (althoug ...

The $http.get() function in Angular fails to function properly when used in Phonegap DevApp

Trying to retrieve a JSON file in my Phonegap App using angulars $http is causing some issues for me. I have set up this service: cApp.factory('language', function ($http) { return { getLanguageData: function () { return ...

Strange actions observed in JavaScript addition operations

In my Angular application, I have the following TypeScript function: countTotal() { this.total = this.num1 + this.num2 } The value of num1 is 110.84 and the value of num2 is 5.54. I determined these values by watching this.num1 and this.num2 in the C ...

Utilizing a Promise in NodeJS and Express to effectively capture the writing functionality of the HTTP module

Currently, I am in the process of developing an Express application with the following components: NodeJS v8 express (latest version) As I delved into the workings of the onHeaders module and observed how it alters the HTTP headers, I became keen on lev ...

Revolutionary custom binding with Bootstrap popover integration

Utilizing asp.net mvc with dynamic knockout columns, I am facing an issue with one of the column headers named "Status". The desired functionality includes a bootstrap popover that displays information when a user clicks a font-icon question mark. Here is ...

pg-promise received an error due to an incorrect parameter being passed in for options

I have been working on transitioning my files from utilizing the pg package to the pg-promise package. Initially, everything was functioning correctly with the original pg solution I had in place. However, upon switching to pg-promise and referencing the d ...

Independent Dropbox Collections

Query: function addRow(tableID) { var table = document.getElementById(tableID); var rowCount = table.rows.length; var row = table.insertRow(rowCount); var colCount = table.rows[0].cells.length; for (var i = 0; i < colCount; i++) { var ...

React component making an Axios request only receives the initial state as a response

I'm struggling with creating an AJAX call using Axios in React. Despite my efforts, I can't seem to pinpoint where the issue lies. Below is what I currently have within my component: ComponentDidMount() { axios.get('https://jsonplacehol ...

Is there a way to enable scanned data to be automatically inputted into a field without manual entry?

I am in the process of creating a user-friendly Android app for virtual inventory management. I want the application to streamline data input by automatically populating text fields upon scanning, eliminating the need for users to manually click on each fi ...

JavaScript payload object's name

Here is the data I have received. {name: "Sinto 6", val: {…}, line: "Sinto 6"} line: "Sinto 6" name: "Sinto 6" val: AvgMachTime: 253 AvgManTime: 1343 CollectMachTimer: 359 CollectManTimer: 108 CycleTimeMach: 359 Cy ...

Vue.js - The error message "$slots have 'el' is null" indicates a problem with the element in

When trying to access the Vuejs $slots instance, I encounter el = null, but type = "div" Here is the template: <slot name="head"> <h1> {{ text }} </h1> </slot> And in the script section: ... ...

Node.js and Mongoose not functioning properly in collaboration

Searching for a user based on matching first and last names. router.post('/post/user/search/tag', function (req, res) { function getRegex(_query) { return { $regex: '^' + _query + '|.*' + _query, $optio ...

Utilizing Angular Components Across Various Layers: A Guide

Consider the following component structure: app1 -- app1.component.html -- app1.component.ts parent1 parent2 app2 -- app2.component.html -- app2.component.ts Is it possible to efficiently reuse the app2 component within the ap ...

Oops! Could not compile due to a syntax error: Invalid assignment expression on the left-hand side

I am currently developing an application that requires me to retrieve data from the backend containing a userdetail object. In my code, I need to set a current accessToken for the userdetail object: useEffect(() => { if (session?.user && ...

Material UI DateTimePicker Displaying Incorrectly

I am implementing a new Material UI date time picker on page load by setting the open prop. <Grid item xs={6} className={styles.CampaignDates_calendar_right}> <MuiPickersUtilsProvider utils={DateFnsUtils} className={styles.CampaignDates_calendar ...

Is nesting directives possible within AngularJS?

Having trouble creating a Directive that includes another directive from the AngularJS UI. Check out my html: <div class="col-md-12" ng-show="continent == '2'"> <my-rating></my-rating> </div> Here is the directiv ...

Is there a way to ensure seamless animation when dynamically adding components in react native?

I am working on a React Native application where I have implemented a card with a conditional <Text> component. This text is rendered when a button is pressed and removed when the same button is triggered again. Below is a snippet of my code: <V ...