Skip to content

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

@ShenQingchuan

Description

@ShenQingchuan

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;

Metadata

Metadata

Assignees

No one assigned

    Labels

    need reproReproduction code is required

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions