vue-component - Vuex。如何使用 v-for 从 store 渲染数据

标签 vue-component vue.js

我有几个组件的应用程序。我使用 Vuex 来存储数据,这样我就可以在不同的组件中使用它。现在我需要使用 v-for 渲染一些 div。我是这样做的:

VueX/Modules/shows.js

const state = {
 shows: [
  {
   name: 'Hard Luck',
   venue: 'The Venue',
   time: '6:00 pm'
  },
  {
   name: 'Hard Luck',
   venue: 'The Venue',
   time: '6:00 pm'
  }
 ]
}

export default {
 state
}

我需要使用数据的组件:

  <template>
   <div class="dashboard__details dashboard__details--shows"
      v-for="show in shows">
    <h3 class="dashboard__name">
       {{show.name}} @ {{show.venue}}      
     </h3>
     <span class="dashboard__time">{{show.time}}</span>
     <div class="dashboard__btnBlock">
       <button">Details</button>
     </div>
    </div>
   </template>

   <script>
   import { mapState } from 'vuex'
   import ReportIssue from './ReportIssue'
   import InviteFriend from './InviteFriend'

   export default {
     name: 'dashboard',
     components: { ReportIssue, InviteFriend },
     computed: mapState({
       shows: state => {
        return state.shows
       }
     })
   }
   </script>

如果我在组件的数据中有数据,它就可以工作,但如果我将数据存储在 Vuex 中,我就不能让它工作。

最佳答案

如果您正在使用一个模块,那么您需要在您的商店中配置它:

# your Vuex store
import shows from './VueX/Modules/shows.js'
export default new Vuex.Store({
  modules: {
    shows,
  },
  ...

然后,当您在组件中引用它时,您调用的是模块而不是根状态:

export default {
  name: 'dashboard',
  components: { ReportIssue, InviteFriend },
  computed: mapState({
    shows: ({ shows }) => shows.shows
  })
}

您可能想重命名模块以避免 shows.shows 但您应该明白这一点

关于vue-component - Vuex。如何使用 v-for 从 store 渲染数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40707578/

相关文章:

javascript - 当我想传递参数时,路由器推送在 vuejs 中不起作用

javascript - 有没有办法覆盖 vue 组件内的转换

表单提交后验证重置

javascript - 如何在 Vue 中使过滤列表更具动态性

javascript - 在所有页面上包含 Vue js 实例,即使元素不存在

javascript - 如何锁定 Kendo UI Vue Grid 中的列( native )

vue.js - Vue 路由器使用 keep-alive 来缓存某些组件?

javascript - VueJS - 如何在脚本标签中获取单个文件组件的实例

vue.js - vue-instagram : images showing as icons, 即使 src/url 是正确的

vue.js - 在 vitest 中使用模拟模块