Vuex.如何使用 v-for 从存储中渲染数据

2022-01-25 00:00:00 vue.js vue-component

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

I have app with couple components. I use Vuex to store data so I could use it in different components. Now I need to render some divs using v-for. I do as follows:

VueX/Modules/shows.js

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
}

我需要使用数据的组件:

Component where I need to use data:

  <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 中,我将无法使其工作.

It works if I have data in the component's data but I can't make it work if I store data in Vuex.

推荐答案

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

if you are using a module then you need to of configured that within your store:

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

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

Then when you reference it within a component you call the module not the root state:

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

你可能想重命名模块以避免 shows.shows 但你应该明白

You probably want to rename the module so to avoid shows.shows but you should get the idea

相关文章