【问题标题】:computed property returns empty array计算属性返回空数组
【发布时间】:2021-02-16 18:21:36
【问题描述】:

我在 VueJS 中有一个这样的计算属性:

  computed: {
    groupedTemplates() {
      const ret = this.templates.reduce((acc, value) => {
        value.group = value.group || "Ungrouped";
        if (!acc[value.group]) {
          acc[value.group] = [];
        }
        acc[value.group].push(value);
        return acc;
      }, []);
      console.log(ret);   // <---- This works!!
      return ret;
    },
    ...mapState(["currentPatient", "currentSite", "phrases", "templates"]),
  },

当我查看控制台时,我可以看到正确的响应是 app.js:4061 [Ungrouped: Array(6), Note: Array(2), Order Set: Array(3)]

但是,当我在代码中使用 groupedTemplates 时,它的计算结果为 []

当我将返回线改为

return 34;

它按预期返回 34。什么给了?

【问题讨论】:

    标签: vuejs2 computed-properties


    【解决方案1】:

    因为您的reduce 不会将项目添加到数组中,而是在Array 对象上创建新的属性 - 您不能将use a string as an index 放入数组中...

    您可能想要的是从您的 groupedTemplates 计算返回 Object...

    【讨论】:

    • 哇!很棒的接机!谢谢!但是我怎么能用 console.log 看到呢?
    • 控制台只显示具有所有属性的对象......
    猜你喜欢
    • 2014-06-18
    • 2019-02-14
    • 1970-01-01
    • 1970-01-01
    • 2018-02-03
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 2020-01-04
    相关资源
    最近更新 更多