Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional route in Vue.js

I have two different views that I'd like to show for the same path depending on whether a token is in LocalStorage or not. I could move the logic directly into the view itself, but I was curious to know whether there's a way to it in the Router.

Something like:

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

I tried with the above code but didn't work. The app builds fine but none of the two views is shown.

like image 886
Edgar Derby Avatar asked Dec 02 '18 09:12

Edgar Derby


Video Answer


2 Answers

A getter could be used for this, but, you will need to be sure to import both components:

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 notes, I have written "cannot find documentation on this" pertaining to the above. While not specifically related, however, it might be helpful to review using some information from https://stackoverflow.com/a/50137354/3261560 regarding the render function. I've altered what is discussed there using your example above.

component: {
    render(c) {
        if (...) {
            return c(ViewA);
        } else {
            return c(ViewB);
        }
    }
}
like image 58
John Shipp Avatar answered Sep 27 '22 22:09

John Shipp


I was answering the same question before and you can see it here.

Here is an example:

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

        next();
      }
    },

... where A, B, C are components and they are randomly chosen every time the route changes. So in your case you can just alter beforeEnter logic to your needs and set any component you wish before routing to it.

like image 27
AndrewShmig Avatar answered Sep 27 '22 22:09

AndrewShmig