Background

我创建了一个router / index.js文件,并为我的Vue应用程序创建了一个路由器 . 我将VueX添加到应用程序中,并在整个组件中使用它 . 我想在路由器中使用getter来检查登录用户的权限,但是我无法正确导入VueX .

Problem

当我将我的商店和模块重要到路由器文件 index.js 时,我正在尝试使用 this.$store.registerModule() . 当我尝试这个时,我在 this.$store 上得到了未定义 .

Example

import Vue from 'vue';
import Router from 'vue-router';
import { mapGetters } from 'vuex';
import authentication from '../store/modules/authentication';
import store from '../store';


if (!(store && store.state && store.state[name])) {
  this.$store.registerModule(name, authentication);
}

这个逻辑适用于我使用它的任何Vue组件,但它在路由器文件中不起作用 .

我的目标是能够像这样检查VueX中的状态,

const getters = {
  ...mapGetters('authentication', ['IS_LOGGED_IN'])
};

const router = new Router({
{
      path: '/admin',
      name: 'Admin',
      component: Admin,
      meta: {
        requiresAuth: true,
        isAdmin: true
      }
  ]
});


router.beforeEach((to, from, next) => {
  if (
    to.matched.some(record => record.meta.requiresAuth) &&
    to.matched.some(record => record.meta.isAdmin)
  ) {
    if (!getters.IS_LOGGED_IN && !getters.IS_ADMIN) {
      next({
        path: '/login',
        params: { nextUrl: to.fullPath }
      });
    } else {
      next();
    }
  } else if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!getters.IS_LOGGED_IN) {
      next({
        path: '/login',
        params: { nextUrl: to.fullPath }
      });
    } else {
      next();
    }
  } else if (to.matched.some(record => record.meta.guest)) {
    next();
  } else {
    next();
  }
});

export default router;

Question

将VueX与Vue Router一起使用的正确方法是什么?

Things I tried

我试过用,

store.registerModule(name, authentication);

抛出未定义, registerModule