【问题标题】:Access to Vuex store state from a component using Nuxt使用 Nuxt 从组件访问 Vuex 存储状态
【发布时间】:2018-12-31 15:44:32
【问题描述】:

我正在尝试将按钮名称列表从 Vuex 商店传递到 https://nuxtjs.org/guide/vuex-store 之后的菜单组件中

我的 /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   

【问题讨论】:

  • 有什么问题?
  • @BoussadjraBrahim 是不是更清楚了?
  • 是的,这很清楚,但我建议将商店代码分享为文本而不是屏幕截图
  • 非常感谢!
  • 来自那些文档-> 我们不需要安装 vuex,因为它是随 Nuxt.js 一起提供的。我们现在可以在我们的组件中使用 this.$store:

标签: javascript vue.js vuejs2 vuex nuxt.js


【解决方案1】:

我建议使用一个名为 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
                              // ^___________

  }
 }
}

【讨论】:

    【解决方案2】:

    更好的选择可能是

    import {mapGetters} from 'vuex';
    

    并使用类似

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

    【讨论】:

      猜你喜欢
      • 2021-06-17
      • 2017-12-05
      • 2021-04-21
      • 2020-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-28
      • 2019-05-02
      相关资源
      最近更新 更多