简体   繁体   English

尝试读取 vuex state 时未定义

[英]Getting undefined when trying to read vuex state

Following a simple example in VueMaster course and can't seem to read state from the store.按照 VueMaster 课程中的一个简单示例,似乎无法从商店中读取 state。 Here's my main.js:这是我的 main.js:

import Vue from 'vue'
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'
import App from './App.vue'
import router from './router'
import store from './store'

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

And here's my index.js in the /store folder:这是我在 /store 文件夹中的 index.js:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user: { id: 'abc123', name: 'Adam Jahr' },
  },
  mutations: {},
  actions: {},
  modules: {}
})

Then, I try and read the state object from a component:然后,我尝试从一个组件中读取 state object :

<template>
  <div>
    <h1>Create an Event, {{ $store.state.user.name }}</h1>
  </div>
</template>

I don't see anything in the browser for the component.我在浏览器中看不到该组件的任何内容。 Console shows an error "TypeError: Cannot read property 'name' of undefined".控制台显示错误“TypeError:无法读取未定义的属性‘名称’”。

Any idea why this very simple example doesn't work?知道为什么这个非常简单的例子不起作用吗? Thanks.谢谢。

Shouldn't your import look like this:您的导入不应该是这样的:

import store from './store/index'

since that is where you are creating your store, check the folder structure, maybe that is the problem.因为那是您创建商店的地方,请检查文件夹结构,也许这就是问题所在。

I didn't see any problem with your code, it's working as expected.我没有看到您的代码有任何问题,它按预期工作。

Here is sandbox link - https://codesandbox.io/s/silly-poitras-sosvs?file=/src/App.vue这是沙箱链接 - https://codesandbox.io/s/silly-poitras-sosvs?file=/src/App.vue

You need to provide the store in your component Something in computed like return this.$store.state.user您需要在您的组件中提供商店类似的计算返回 this.$store.state.user

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM