Javascript 在另一个方法中达到变量的内容

Javascript 在另一个方法中达到变量的内容,javascript,vue.js,Javascript,Vue.js,我试图通过Vue方法访问matchData的内容。我能够console.log(this.matchData),但无法获取其内容 当我console.log(this.matchData[0].matchScores[0])在方法readMatchPlayerScoreIds()下时,我得到: vue.runtime.esm.js?2b0e:619[vue warn]:挂载的钩子中出现错误:“TypeError:无法读取未定义的属性'matchScores'” 导出默认值{ 数据(){ 返回{

我试图通过Vue方法访问
matchData
的内容。我能够
console.log(this.matchData)
,但无法获取其内容

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

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

导出默认值{
数据(){
返回{
匹配数据:[],
};
},
方法:{
readMatches(){
数据库集合(“匹配”)
.get()
.然后((queryMatchSnapshot)=>{
queryMatchSnapshot.forEach((doc)=>{
this.matchData=[];
这个是.matchData.push({
awayscore:doc.data().awayscore,
homeScore:doc.data().homeScore,
matchScores:doc.data().matchScores,
})
});
console.log(this.matchData[0].matchScores[0])
});
},
ReadMatchPlayerCoreIds(){
console.log(this.matchData[0].matchScores[0])
}
},
安装的(){
这个.readMatches();
这个.readMatchPlayerScoreId();
},
};

由于您是从数据库异步获取数据,因此在数据库调用完成之前,数据将为空。您应该在承诺得到解决后阅读数据。(将我的评论改写为答案)

一种方法是从
readMatches
返回承诺:

    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());
  },
};
导出默认值{
数据(){
返回{
匹配数据:[],
};
},
方法:{
readMatches(){
返回db.collection(“匹配项”)
.get()
.然后((queryMatchSnapshot)=>{
queryMatchSnapshot.forEach((doc)=>{
//this.matchData=[];//this.readMatchPlayerCoreIds());
},
};
但这取决于您希望在
readMatchPlayerScoreIds
方法体中执行的操作


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

您在哪里/如何调用这两种方法?嗨@Daniel_Knights,谢谢您的重播。我已经更新了帖子。在加载matchData之前,您正在调用
readMatchPlayerScoreIds
。我想db调用是异步的,不是吗?需要一个快速修复方法在
内调用
readMatchPlayerScoreIds
,然后在设置数据后调用
块。你说得对,这成功了。谢谢你-你救了我一天!在你写的时候,这是异步数据库。我可能需要在这里编辑帖子的主题。你建议我如何继续,从readMatches()存储数据,然后“推送”是否需要ReadMatchPlayerCoreIDS()?@ChristofferEndresen使用承诺。@如果答案有帮助,ChristofferEndresen可以随意接受:)