0

What I want to achieve is that when accessing /self, it should first check if issignedin is true and then get the value of user.name to redirect. Those variables are set in Vue's data(){... part. Nevertheless, I wasn't able to figure out, how I could access the data since the Vue Instance is created after I create the routes:

const routes = [
//...
  {
    path: "/self",
    redirect: (to) => {
      if (app.issignedin) { 
        return "/@" + user.name;
      } else {
        return "/login";
      }
    },
  },
];
const router = new VueRouter({
  routes,
});

const app = new Vue({
  router: router,
  data() {
    return {
      issignedin: true,
      user: { name: "MoPaMo" },
//...
    };
  },

Neither this nor the name of the variable holding Vue (app) nor something like this.$parent works... :(

Help will be deeply appreciated!

4
  • Try before enter. You basically need navigational gaurds in vue.js. check router.vuejs.org/guide/advanced/navigation-guards.html Commented Jun 3, 2021 at 19:47
  • But don't I have the same problem with Navigation Guards? Commented Jun 3, 2021 at 19:47
  • Why should it? You should revive your system flow. In order to access a particular url, first some data should be present. The vue will load on / and I don't understand why any user would directly type/self to land on your route before vue load Commented Jun 3, 2021 at 20:01
  • Imagine that it's deployed in example.com with a welcome home page and a button or link to go to example.com/self usually web portals work like that. And if you want user data then it usually comes from server api with an async call Commented Jun 3, 2021 at 20:03

1 Answer 1

1

Vue Router 3 provides router.app to access the app instance that installs the router, and you could use that to access app.issignedin.

You could do:

let router = null

const routes = [
  //...
  {
    path: "/self",
    redirect: (to) => {
      if (router.app.issignedin) { 
        return "/@" + user.name;
      } else {
        return "/login";
      }
    },
  },
];

router = new VueRouter({
  routes,
});

Or if you prefer to keep router a const, use a regular function after the router declaration, which captures the router instance within:

const routes = [
  //...
  {
    path: "/self",
    redirect: redirectIfNotSignedIn,
  },
];

const router = new VueRouter({
  routes,
});

function redirectIfNotSignedIn() {
  if (router.app.issignedin) { 
    return "/@" + user.name;
  } else {
    return "/login";
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.