vuejs/vuex

How to access Vuex store in VueRouter.beforeEach in TypeScript?

ShenQingchuan opened this issue · 3 comments

What problem does this feature solve?

I want to set a guard in VueRouter.beforeEach(), it will redirect to the login page when the loggedIn state is false.

What does the proposed API look like?

I want to achieve something this this:

import { RouteRecordRaw, createRouter, createWebHistory } from "vue-router";
import store from "@/store";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/login",
    name: "Login",
    component: () => import("../views/Login.vue")
  },
  {
    path: "/",
    name: "Home",
    component: () => import("../views/Home.vue"),
    meta: {
      requiresAuth: true
    }
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
});

router.beforeEach((to, from, next) => {
  const loggedIn = store.state.authentication.loggedIn;
  if (to.matched.some(record => record.meta.requiresAuth) && !loggedIn) {
    next({
      name: "Login",
      query: { redirect: to.fullPath }
    });
  } else {
    next();
  }
});

export default router;

just similar to #1841 , and that issue hang on for a long while...

Sorry what problem are you having at the moment? Are you getting Object is possibly null error? Either way, please provide reproduction code so that we can test this 🙏 Not just this single file, but we need whole project.

What problem does this feature solve?

I want to set a guard in VueRouter.beforeEach(), it will redirect to the login page when the loggedIn state is false.

What does the proposed API look like?

I want to achieve something this this:

import { RouteRecordRaw, createRouter, createWebHistory } from "vue-router";
import store from "@/store";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/login",
    name: "Login",
    component: () => import("../views/Login.vue")
  },
  {
    path: "/",
    name: "Home",
    component: () => import("../views/Home.vue"),
    meta: {
      requiresAuth: true
    }
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
});

router.beforeEach((to, from, next) => {
  const loggedIn = store.state.authentication.loggedIn;
  if (to.matched.some(record => record.meta.requiresAuth) && !loggedIn) {
    next({
      name: "Login",
      query: { redirect: to.fullPath }
    });
  } else {
    next();
  }
});

export default router;

Hello,is this problem solve?I have the same problem ,can you tell me the sln? Thanks!