Vuex.如何使用 v-for 从商店渲染数据 [英] Vuex. How to render data from store using v-for

查看:36
本文介绍了Vuex.如何使用 v-for 从商店渲染数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

VueX/Modules/shows.js

const state = {显示: [{name: '幸运',场地:场地",时间:'下午 6:00'},{name: '幸运',场地:场地",时间:'下午 6:00'}]}导出默认{状态}

我需要使用数据的组件:

 <模板><div class="dashboard__details 仪表板__details--shows"v-for="在节目中展示"><h3 class="dashboard__name">{{show.name}} @ {{show.venue}}<span class="dashboard__time">{{show.time}}</span><div class="dashboard__btnBlock"><按钮">详细信息</按钮>

</模板><脚本>从 'vuex' 导入 { mapState }从'./ReportIssue'导入报告问题从 './InviteFriend' 导入 InviteFriend导出默认{name: '仪表板',组件:{ ReportIssue, InviteFriend },计算:地图状态({显示:状态 =>{返回 state.shows}})}

如果我在组件的数据中有数据,它就可以工作,但如果我将数据存储在 Vuex 中,它就无法工作.

解决方案

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

# 你的 Vuex 商店从./VueX/Modules/shows.js"导入节目导出默认新 Vuex.Store({模块:{显示,},...

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

出口默认{name: '仪表板',组件:{ ReportIssue, InviteFriend },计算:地图状态({显示:({ 显示}) =>节目.shows})}

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

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

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>

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

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

这篇关于Vuex.如何使用 v-for 从商店渲染数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆