使用 Nuxt 从组件访问 Vuex 存储状态

Access to Vuex store state from a component using Nuxt

我正在尝试将按钮名称列表传递到 https://nuxtjs.org/guide/vuex-store

之后的 Vuex 商店的菜单组件中

我的/store/store.js:

export const state = () => ({
    'toolbarActions' : [ 'My project', 'Home', 'About', 'Contact' ]
})

我的菜单组件:

<template>
  <v-toolbar color="indigo" dark>
    <v-toolbar-side-icon></v-toolbar-side-icon>
    <v-toolbar-title class="white--text">Title</v-toolbar-title>
    <v-spacer></v-spacer>
    <v-toolbar-items class="hidden-sm-and-down">
       <v-btn flat v-for="action in toolbarActions" :key="action">{{action}}</v-btn>
             <!-- <v-btn flat v-for="action in toolbarActions">{{action}}</v-btn> -->
      <!-- <v-btn flat>Link One</v-btn>
      <v-btn flat>Link Two</v-btn>
      <v-btn flat>Link Three</v-btn> -->
    </v-toolbar-items>
  </v-toolbar>
</template>

<script>

// import toolbarActions from '~/store/store.js'

export default {
computed: {
  toolbarActions() {
          return this.$store.state.toolbarActions

          // return [ 'My project', 'Home', 'About', 'Contact' ]
  }
  }
}
</script>

如果我取消注释:

      // return [ 'My project', 'Home', 'About', 'Contact' ]

和评论:

          return this.$store.state.toolbarActions

按钮名称被传递到组件中。但是

 return this.$store.state.toolbarActions

未评论,没有传入任何内容。

如何访问此处的 Vuex 存储以传入按钮名称?

编辑:我进行了更改,我得到:

   ERROR  [Vue warn]: Error in render: "TypeError: Cannot read property 
 'toolbarActions' of undefined"                                                                                                           
  11:52:20

  found in

 ---> <Menu> at components/menu.vue
   <Default> at layouts/default.vue
     <Root>

 » store\_toolbar.js   

我建议使用名为 toolbar 的模块,在其中放入以下代码:

  export const state = () => ({
     'toolbarActions' : [ 'My project', 'Home', 'About', 'Contact' ]
   })

文件夹结构应该是这样的:

.
.
> static
v store
  |_toolbar.js

你的 computed 属性 应该是这样的:

computed: {
  toolbarActions() {
      return this.$store.state.toolbar.toolbarActions  //look i added the name of the toolbar module
                              // ^___________

  }
 }
}

更好的选择可能是

import {mapGetters} from 'vuex';

并使用类似

computed:mapGetters({
    toolbarActions:'toolbar/toolbarActions'
})