【问题标题】:Reach content of variable in another method用另一种方法达到变量的内容
【发布时间】:2020-10-12 14:10:36
【问题描述】:

我正在尝试通过 Vue 方法获取 matchData 的内容。我可以console.log(this.matchData),但无法获取其内容。

当我在方法readMatchPlayerScoreIds()console.log(this.matchData[0].matchScores[0]) 我得到:

vue.runtime.esm.js?2b0e:619 [Vue 警告]:挂载钩子错误:“TypeError:无法读取未定义的属性 'matchScores'”

export default {
  data() {
    return {
      matchData: [],
    };
  },
  methods: {
    readMatches() {
      db.collection("matches")
        .get()
        .then((queryMatchSnapshot) => {
          queryMatchSnapshot.forEach((doc) => {
            this.matchData = [];
            this.matchData.push({
              awayscore: doc.data().awayscore,
              homeScore: doc.data().homeScore, 
              matchScores: doc.data().matchscores,
            })
          });
          console.log(this.matchData[0].matchScores[0])
        });
      },

      readMatchPlayerScoreIds() {
          console.log(this.matchData[0].matchScores[0])
      }
  },
  mounted() {
    this.readMatches();
    this.readMatchPlayerScoreIds();
  },
};

【问题讨论】:

  • 你在哪里/如何调用这两种方法?
  • 嗨@Daniel_Knights,感谢您的重播。我已经更新了帖子。
  • 您在 matchData 加载之前调用了readMatchPlayerScoreIds。我想 db 调用是异步的,不是吗?快速解决方法是在设置数据后在 then 块内调用 readMatchPlayerScoreIds
  • 你说得对,这行得通。谢谢 - 你拯救了我的一天!正如您所写,这是异步数据库。我可能需要在这里编辑帖子的主题。你如何建议我继续从 readMatches() 存储数据,然后将其“推送”到 readMatchPlayerScoreIds()?
  • @ChristofferEndresen 使用承诺。

标签: javascript vue.js


【解决方案1】:

由于您是异步从 db 中获取数据,因此在 db 调用完成之前,数据将为空。你应该在 Promise 解决后读取数据。 (将我的评论重新表述为答案)。

一种方法是从readMatches返回Promise:

    export default {
  data() {
    return {
      matchData: [],
    };
  },
  methods: {
    readMatches() {
      return db.collection("matches")
        .get()
        .then((queryMatchSnapshot) => {
          queryMatchSnapshot.forEach((doc) => {
            // this.matchData = []; // <= why would you reset it in each loop?
            this.matchData.push({
              awayscore: doc.data().awayscore,
              homeScore: doc.data().homeScore, 
              matchScores: doc.data().matchscores,
            })
          });
          console.log(this.matchData[0].matchScores[0])
        });
      },

      readMatchPlayerScoreIds() {
          console.log(this.matchData[0].matchScores[0])
      }
  },
  mounted() {
    this.readMatches()
        .then(() => this.readMatchPlayerScoreIds());
  },
};

但这取决于你想在readMatchPlayerScoreIds 方法体中做什么。

另外,请注意不要在 forEach 循环中重置 matchData

【讨论】:

  • @ChristofferEndresen 如果有帮助,请随时接受答案:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-10
  • 1970-01-01
相关资源
最近更新 更多