【发布时间】:2018-07-06 20:34:57
【问题描述】:
我正在尝试访问 Vuex 商店,如本文所示:here
我已经浪费了一个早上好,我确信这将是一个简单的错字,但它逃脱了我。在 beforeEach() => {} 体内,我得到“未定义存储”。
我正在使用 LoginForm 组件中的商店,它似乎在那里。 chrome 调试器中的 Vuex 选项卡显示了我期望的商店内容。我做错了什么?
从关键代码中剪切粘贴:
src/router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import LoginForm from '@/components/LoginForm'
import HomePage from '@/components/HomePage'
import store from '@/store'
Vue.use(VueRouter)
const router = new VueRouter({
routes: [
{
path: '/login',
component: LoginForm
},
{
path: '/home',
component: HomePage,
meta: {requiresAuth: true}
}
]
})
router.beforeEach((to, from, next) => {
// store is undefined here
const IsAuthenticated = store.getters.IsAuthenticated()
if (to.matched.some(record => record.meta.requiresAuth) && !IsAuthenticated) {
next({path: '/login', query: { redirect: to.fullPath }})
} else {
next()
}
})
export default router
编辑: 商店的出口似乎没问题。通过保持对导入商店的本地引用并引用它,它可以工作。在我使用 beforeEach() 时似乎与上下文有关。
const lStore = store;
router.beforeEach((to, from, next) => {
// store is undefined here, lStore is good to go
const IsAuthenticated = lStore.getters.IsAuthenticated()
...
})
【问题讨论】:
-
通过存储本地引用找到了解决方法。我会编辑我的问题。道具 paeloque 让我专注于此。
-
谢谢...本地商店解决了这个问题....
-
在我的情况下,当你调试时,商店确实在 Chrome 工具中评估为 undefined,但实际上当这段代码运行时,它发现商店很好!这可能是一些 Chrome 内存优化,因为这个商店应该被包装到一个闭包中
标签: vue.js vue-router vuex