代码之家  ›  专栏  ›  技术社区  ›  user742030

Vuex Getters返回未定义

  •  0
  • user742030  · 技术社区  · 6 年前

    如果 mapGetters() 如果注释掉(如下面的示例代码),则返回的数据将显示在屏幕上->如果用户单击包含数据的链接。如果用户在数据应该显示的地方直接进入应用程序,数据将不会显示。

    有一个 similar question 但没有一个公认的答案

    Vue控制台日志:

    国家:

    $_lgdHRS:对象

    总计:129


    美元/totHrs:未定义

    <script>
    import store from '../../_store'
    import { mapState, mapGetters } from 'vuex'
    
    export default {
      computed: {
        ...mapState('$_lgdHRS',{
          totHrs : 'totHrs',
        }),
    
      // ...mapGetters('$_lgdHRS',{
      //    totHrs  : 'totHrs',
      //    airHrs  : 'airHrs',
      //    picHrs  : 'picHrs',
      //    pmcHrs  : 'pmcHrs',
      //    voHrs   : 'voHrs',
      //    trngHrs : 'trngHrs'
      // }),
      },
    
      created() {
        this.storeKey = '$_lgdHRS';
          if (!(this.storeKey in this.$store._modules.root._children)) {
            this.$store.registerModule(this.storeKey, store);
        }
      },
    
      mounted() {
        this.$store.dispatch('$_lgdHRS/getLogSummary');
      },
    }
    </script>
    <template>
        <total-summary :hours="totHrs" />
    </template>
    

    状态.js

    export const state = {
      totHrs: Number,
    }
    

    const totHrs = state => state.totHrs;
    export default {
      totHrs,
    };
    

    突变.js

    const
    TOTAL_HRS_UPDATED = (state, totHrs) => {
      state.totHrs = +totHrs;
    };
    export default {
        TOTAL_HRS_UPDATED,
    };
    
    2 回复  |  直到 4 年前
        1
  •  0
  •   Riddhi    6 年前

    很可能是因为您刚刚在mounted中发送了请求,并且在将数据设置为state变量之前,您的组件就会显示出来。 因此,您可以尝试使用async await in mounted和in-store操作。 https://vuex.vuejs.org/guide/actions.html

        2
  •  0
  •   user742030 user742030    6 年前

    问题是我像通常在其他框架中那样嵌套变量。

    // NESTED VARS
    const r = response
          totHrs  = r.total,
          airHrs  = r.airborne,
          picHrs  = r.PIC,
          pmcHrs  = r.PMC,
          voHrs   = r.VO,
          trngHrs  = r.training;
    
    // CHANGE TO:
    const r = response
    const totHrs  = r.total
    const airHrs  = r.airborne
    const picHrs  = r.PIC
    const pmcHrs  = r.PMC
    const voHrs   = r.VO
    const trngHrs = r.training
    

    我不知道为什么,但你的意见将非常感谢你的意见。