【问题标题】:Can i dynamically call a getter using mapGetters in Vue/Vuex?我可以在 Vue/Vuex 中使用 mapGetters 动态调用 getter 吗?
【发布时间】:2019-11-18 16:48:23
【问题描述】:

我的组件模板:

<template>
  <section class="stage my-5">

      <div class="stage-heading">
        <h3 class="stage-number mb-4">Stage {{stage}}</h3>
        <h6 class="stage-hrs">Total Hrs: {{totalHours}}</h6>
      </div>

      <div class="stage-courses card text-white bg-info mb-3" v-for="course in courses" :key="course.id">
        <div class="card-header">Stage {{course.stage}}</div>
        <div class="card-body">
          <h5 class="card-title">{{course.title}}</h5>
          <p class="card-text">{{course.creator}}</p>
          <p class="card-text">{{course.hours}} Hours</p>
        </div>
      </div>

    </section>
</template>

我的 Vuex 商店中的状态:

const state = {
  roadmapStage1: [], 
  roadmapStage2: [],
  roadmapStage3: [],  
};

我的 Vuex 商店中有 getter,如下所示:

getRoadmapStage1: state => state.roadmapStage1,
getRoadmapStage2: state => state.roadmapStage2,
getRoadmapStage3: state => state.roadmapStage3,

我正在尝试从组件中动态调用其中一个 getter,这取决于组件的 prop:

export default {
  name: "Stage",
  data() {
    return {
      courses: []
    }
  },
  props: ['stage'],
  computed: mapGetters({courses: 'getRoadmapByStage'})
}

有没有办法将道具插入到“getRoadmapByStage”中?例如所以它的功能类似于 getRoadmapByStage${stage}?

最终我试图让组件在更新路线图阶段数组的任何时候重新渲染。谢谢!

【问题讨论】:

    标签: javascript vue.js vuex


    【解决方案1】:

    我建议使用带有参数的 getter 来返回您想要的路线图的阶段 id/编号,如下所示:

    // in getters.js
    //gets the current roadmap based on the stage number
    getRoadmapByStage: (state) => (stageNumber) => {
        return state["roadmapStage" + stageNumber];
    }
    

    现在在你的组件中你可以拥有:

    computed: {
       currentRoadmap() {
          // now we'll pass in your 'stage' prop to get the appropriate map
          // this will re-render the component as that prop changes
          return this.$store.getters.getRoadmapByStage(this.stage);
       }
    }
    

    【讨论】:

    • 谢谢,我的组件没有重新渲染或显示任何内容。我认为这是因为“课程”数据没有被更改,而 v-for 依赖于该数据。我已经编辑了我的问题以显示模板。我是否需要在currentRoadmap() 中设置状态而不是仅仅返回它? Vue 目前让我很困惑!
    • 算了!我想通了,只需将v-for="course in courses" 更改为v-for="course in currentRoadmap"。非常感谢!
    【解决方案2】:

    您可以按如下方式声明您计算的roadmap 属性:

    computed: {
      roadmap() {
        return this.stage ? this.$store.getters['getRoadmapByStage' + this.stage] : undefined
      },
    }
    

    这样您就可以通过 prop 的值或 undefined 如果 prop 未设置任何值来获取路线图。

    【讨论】:

      猜你喜欢
      • 2020-11-22
      • 2016-08-10
      • 2019-03-05
      • 2021-07-15
      • 2020-09-21
      • 2020-09-03
      • 2019-02-02
      • 1970-01-01
      • 2018-01-08
      相关资源
      最近更新 更多