【问题标题】:Cannot read properties of undefined (reading '$store')无法读取未定义的属性(读取“$store”)
【发布时间】:2021-11-15 07:05:46
【问题描述】:

您好,我收到此错误无法读取未定义的属性(读取“$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);
    }
  }

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

【问题讨论】:

标签: vue.js vuex vue-router


【解决方案1】:

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

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

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

if(!store.state.user){
 next('/401');
}

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

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);
    }
  }
}

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

【讨论】:

    【解决方案2】:

    @MaseehaTasneem 您可以从 next() 函数中访问内部结构,如下所示。 试试下面的,看看你有什么可用的。你也许可以做类似的事情,

    beforeRouteEnter(to, from, next) {
     next(vm => {
       console.log("vue model", vm)
       
       if (vm.$store.state.authenticated.admin === true) {
         return '/home'
       }
    
       return false
     }) 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-11
      • 2022-01-15
      • 2021-12-31
      • 2021-12-13
      • 2021-11-28
      • 2021-11-06
      • 2021-11-20
      • 2021-11-16
      相关资源
      最近更新 更多