Vue.js Conditional RoutingIn Vue.js, conditional routing allows

I'm currently facing a challenge where I want to display two different views for the same path based on the presence of a token in LocalStorage. While I could easily handle this logic within each view itself, I'm exploring the possibility of achieving this directly in the Router.

Here's an example:

export default new Router({
  mode: "history",
  base: process.env.BASE_URL,
  routes: [
    {
      path: "/",
      name: "home",
      component: function() {
        if (...) {
          return ViewA
        } else {
          return ViewB
        }
      }
    },
  ]
});

I've attempted the above code but unfortunately, it didn't work as expected. The application builds without error, but neither of the two views is being displayed.

Answer №1

To handle this situation, the use of a getter would be appropriate, ensuring that both components are imported:

import ViewA from '@/views/ViewA'
import ViewB from '@/views/ViewB'

export default new Router({
    mode: "history",
    base: process.env.BASE_URL,
    routes: [
        {
            path: "/",
            name: "home",
            get component() {
                if (...) {
                    return ViewA;
                } else {
                    return ViewB;
                }
            }
        },
    ]
});

In my personal notes, I've made a remark stating "cannot find documentation on this" in relation to the above code snippet. While not directly related, you may find it beneficial to explore information from concerning the render function. By adapting the discussion there to your specific scenario provided above.

component: {
    render(c) {
        if (...) {
            return c(ViewA);
        } else {
            return c(ViewB);
        }
    }
}

Answer №2

After some experimentation, I discovered a straightforward approach to achieve this by leveraging the webpack lazy loading feature in vue router alongside a vuex store state property.

{
  path: '/',
  component: () => { 
    if (store.state.domain) {
      return import(/* webpackChunkName: "app-home" */ '../views/AppHome.vue');
    } else {
      return import(/* webpackChunkName: "home" */ '../views/Home.vue');
    }
  }
},

By implementing the code above, I was able to dynamically import my home component and determine the route component based on the value of the domain property within my vuex store. It is important to ensure that you have properly set up your vuex store and imported it into your router for this method to function correctly.

The original solution provided in the inquiry would have been successful if the component was returned as an import.

Answer №3

I previously addressed a similar question and my response can be found here.

Below is an illustration:

routes: [
    {
      path: '*',
      beforeEnter(to, from, next) {
        let components = {
          default: [X, Y, Z][Math.floor(Math.random() * 100) % 3],
        };
        to.matched[0].components = components;

        next();
      }
    },

... where X, Y, Z represent components that are randomly selected each time the route changes. For your scenario, you have the flexibility to customize the beforeEnter logic as per your requirements and assign any desired component before routing to it.

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

An npm list is always full of modules

As I prepare to install a package using npm, I noticed that my folder for the new project already has numerous items listed when I run npm list. Is it normal for the folder not to be empty at this stage? Have I made an error somewhere? ...

Using jQuery to hide individual elements within a group of elements with the same class based on specific text contained within them

Here is a demonstration of the task at hand - the HTML code: <div id="section"> <div class="test-row"> <div class="row-copy-options"> <h4 class="text-capitalize"><b>Test Heading 1</b></h4> ...

Error message "The camera provided is invalid and not an instance of THREE.Camera" appears when attempting to render a cube using Three.js

I've been working on a small "engine" project using three.js to easily create and position objects. So far, I have set up the scene, renderer, and camera successfully. However, when attempting to render and attach a cube to my scene, I encounter an is ...

Is the disable feature for React buttons not functioning properly when incorporating Tailwind CSS?

import React, { useState } from "react"; import facebook from "../UI/icons/facebook.png"; import Button from "../UI/Button/Button"; import Card from "../UI/Card/Card"; import twitter f ...

Switch between multiple unordered lists (ul) so that when one list is clicked, the other lists reset to their initial state as though they were never

When I click on the first item in the ul list, it should slideToggle() to show its corresponding items. Similarly, when I click on the second item in the ul list, its items should slideToggle(), but the first ul list remains visible as well. What I am tryi ...

Struggling with making the ajax request

Having trouble handling the response from a URL called through AJAX. The URL returns a response when accessed directly from the browser, but encountering difficulties when using it in the AJAX call. Have tried using both responseText and responseXML proper ...

Changes made in React are not reflected in the DOM

import React, { Component } from "react"; import ReactDOM from "react-dom"; import "./index.css"; class App extends Component { constructor(props) { super(props); this.state = { text: "", listItem: [] } this.onChangeInpu ...

When utilizing the ::first-letter pseudo-element on <sub> and <sup> tags

Why is the <sub> and <sup> not supporting the ::first-letter CSS pseudo-element? Any solutions? p:first-letter, sub:first-letter, sup:first-letter { color: red; font-weight: bold; } <p>This text contains <sub>subscript</su ...

GTM - Table - Press a button to extract the text from a different element

I am not a coder, but I'm diving into the world of Google Tag Manager with the aim of tracking button clicks on search results. I have clients who want to monitor interactions with specific products displayed in their search results. While setting up ...

Issue with the positioning of bootstrap popover after content is added

Having trouble writing a function that adds a textarea to the bottom of a popover content when clicking on a button. The issue is that once the textarea is displayed, the popover extends downward and obscures the text. I'm looking for a solution where ...

Animated CSS sidemenu (utilized as a filtering panel for a table)

Hi there, I'm having some trouble with CSS Animation. I recently started developing websites and am using Bootstrap 4 along with Animate.css for animations. My goal is to have an icon button expand sideways to reveal a div containing select elements f ...

Is there a way to use JQuery to determine which button in a table was clicked and retrieve all the data from that specific row?

Below is the HTML code: <table class="table table-stripped table-bordered table-hover centerAll" cellpadding="10"> <thead> <th>Nombre</th> <th>Descripci ...

Tips for fetching data from a database using AJAX when the values of two drop-down lists are involved

I have successfully implemented an Example where I retrieve data using a single drop-down list from a database. Now, I want to extend this functionality to work with two drop-down lists, where the values retrieved from the database are dependent on the sel ...

Retain the user's input in the text box even after the form has been submitted

Currently, I am tackling the challenge of creating a register form with an error handler to manage any mistakes made by users during registration. Once the form is submitted, potential errors are displayed to the user. To enhance user experience, I am ex ...

Utilize the client-side JavaScript file with ejs framework

Recently, I have been working on creating a website using Express and EJS. I discovered that using just one JavaScript file for all my EJS (view) files was causing issues. If I target a DOM element in one view page and it doesn't exist in another, I w ...

Comparing ngrx and redux for managing state in stateless components

Exploring ngrx/angular 8 for the first time, I'm curious to know if the angular approach of using an observable to bind a state value to the this context still allows a component to remain presentational and stateless. In the realm of angular/ngrx, c ...

What are the most effective techniques for utilizing promise.all in your codebase?

When trying to consolidate responses from two API calls in the code below, I'm facing an issue where Promise.all is not being invoked. Any suggestions on what might be implemented incorrectly and the best practice to achieve this using Promise.all? T ...

Specify a preset selection time in a TextField of time type in Material UI

I am looking to establish a default time for a textfield of type time in Material UI. My requirement is that before the user clicks on the picker, no time should be pre-set, but once they click, 08:00 should appear as the default time to choose from. View ...

The Precision of the IRR (Internal Rate of Return) Calculation in Javascript

I've been working on a custom IRR function in JavaScript to mimic the functionality of Excel's IRR function. Despite my best efforts, it seems that my results are slightly off. Below is the code snippet that I have been using: var IRRval = []; ...

Navigate through a JavaScript text file one line at a time

There is a text file with the following content: User:root Password:root123 My goal is to read this text file in JavaScript line by line and store it in an array. Then, I want to split each value in the array using a colon (:). Despite trying multiple a ...