无法读取未定义的属性(读取“$store”)

Mas*_*eem 5 vue.js vue-router vuex

嗨,我收到此错误无法读取未定义的属性(读取“$store”):这是我的路由器(index.js)

{
  path: '/',
  name: 'login',
  component: () => import( /* webpackChunkName: "hours" */ '../views/login.vue'),
  meta: {
    hideNavbar: true,
  },
  beforeEnter: (to, from, next) => {
    if (this.$store.state.authenticated.admin === true) {
      next('/home');
    } else {
      next(false);
    }
  }
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我正在努力导航到主页...收到此错误。这里`TypeError:无法读取未定义的属性(读取'$store')

Sui*_*pps 5

在 vue router 内部,你没有 vue 实例。因此没有办法访问this.$store.state。为了访问您的商店,您需要将 vuex 包含到路由器中。

import store from '@/store/index.js';
Run Code Online (Sandbox Code Playgroud)

然后,要从商店调用数据,您将调用我们刚刚导入的商店变量。例如

if(!store.state.user){
 next('/401');
}
Run Code Online (Sandbox Code Playgroud)

对于你的情况,它看起来像这样:

import store from '@/store/index.js';

{
  path: '/',
  name: 'login',
  component: () => import( /* webpackChunkName: "hours" */ '../views/login.vue'),
  meta: {
    hideNavbar: true,
  },
  beforeEnter: (to, from, next) => {
    if (store.state.authenticated.admin === true) {
      next('/home');
    } else {
      next(false);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我建议也看看这个答案: Accessing Vuex store in Router