尝试读取 vuex 状态时未定义

Getting undefined when trying to read vuex state

正在学习 VueMaster 课程中的一个简单示例,但似乎无法从商店中读取状态。这是我的 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')

这是我的 index.js 在 /store 文件夹中:

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: {}
})

然后,我尝试从组件中读取状态对象:

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

我在浏览器中没有看到该组件的任何内容。控制台显示错误“TypeError:无法读取未定义的 属性 'name'”。

知道为什么这个非常简单的示例不起作用吗?谢谢

您需要在您的组件中提供商店 像计算中的东西 return这个.$store.state.user

您的导入不应该像这样:

import store from './store/index'

因为这是您创建商店的地方,请检查文件夹结构,也许这就是问题所在。

我没有发现您的代码有任何问题,它按预期工作。

这里是沙盒 link - https://codesandbox.io/s/silly-poitras-sosvs?file=/src/App.vue