路由的身份验证中间件不起作用

时间:2019-02-12 16:20:30

标签: javascript vue.js

我正在使用Vue,将Vuex与Quasar一起使用(Quasar在这里可能无关紧要)

这是我的第一个应用程序,所以我不确定我是否做正确的事情

下面是我的路线的代码段

import Vue from 'vue'
import VueRouter from 'vue-router'


Vue.use(VueRouter)

/*
 * If not building with SSR mode, you can
 * directly export the Router instantiation
 */

const routes = [

  {
    path: '/',
    component: () => import('layouts/MyLayout.vue'),
    beforeEnter: ifAuthenticated ,
    children: [
      { path: '', component: () => import('./../container/Index.vue') }
    ]
  }
]

const ifNotAuthenticated = (to, from, next) => {
  console.log("here")
  if (!store.getters.isAuthenticated)  return next()
  else  next('/')
}

const ifAuthenticated = (to, from, next) => {
  if (store.getters.isAuthenticated) return next()
  else  next('/login')
}


export default function (store) {
  const Router = new VueRouter({
    mode: 'history', 
    routes,

    // Leave these as is and change from quasar.conf.js instead!
    // quasar.conf.js -> build -> vueRouterMode
    // quasar.conf.js -> build -> publicPath
    mode: process.env.VUE_ROUTER_MODE,
    base: process.env.VUE_ROUTER_BASE
  })

      return Router
}

请注意这行代码

const ifNotAuthenticated = (to, from, next) => {
  console.log("here")
  if (!store.getters.isAuthenticated)  return next()
  else  next('/')
}

基于此,我期望进行客户端身份验证,并基于对客户端身份验证的了解/了解

我认为当我做这样的事情时会叫

beforeEnter: ifAuthenticated ,

但是不幸的是,该函数没有被调用(因为它不是控制台记录任何东西)。

对我可能做错的事情有任何想法吗?

1 个答案:

答案 0 :(得分:0)

您不会在代码中的任何地方调用ifNotAuthenticated,因此不会看到控制台日志消息。

使用全局beforeEach保护来检查身份验证可能更容易和更好。这是一个非常简单的示例代码,您如何在路由配置中使用meta数据来完成此操作。

我在代码中添加了注释以说明问题。

我建议您阅读Vue Router文档中的Navigation Guards。 不错的article会更详细地说明事情。

const routes = [
  {
    path: "/dashboard",
    name: "Dashboard",
    component: () => import("path/to/Dashboard.vue"),
    // Add a metadata like this to your private routes
    // Tip: If you have a lot of private routes, you can add
    // meta: { public: true } to public routes and make
    // all other routes private by default.
    // In this case you need to change the logic in beforeEach
    // below.
    meta: { requiresAuth: true },
  },
];

export default function(store) {
  const Router = new VueRouter({
    mode: "history",
    routes,
    // Other stuff...
  });

  Router.beforeEach((to, from, next) => {
    // See if any of the matched routes has meta "requiresAuth"
    if (to.matched.some(route => route.meta.requiresAuth)) {
      // Yes this route requires authentication. See if the user is authenticated.
      if (store.getters.isAuthenticated) {
        // User is authenticated, we allow access.
        next();
      } else {
        // User is not authenticated. We can redirect her to
        // our login page. Or wherever we want.
        next("/login");
      }
    } else {
      next();
    }
  });

  return Router;
}