data()中的错误:“ TypeError:this.game.league_person_result [0]未定义”

时间:2019-06-21 23:16:11

标签: vuejs2

想在vuejs2中呈现数据属性

我试图放入数据或计算的属性中,但是它不起作用。

  data() {
    return {
      edit: false,
      leagueGameResult: {
        person_id: this.game.person.id,
        person_result: this.game.person_result,
        opponent_id: this.game.opponent.id,
        opponent_result: this.game.opponent_result,
        game_id: this.game.id,
        league_id: this.$route.params.id,
      },
      leagueGameResultEdit: {
        person_id: this.game.person.id,
        person_result: this.game.person_result,
        person_result_id: this.game.league_person_result[0].id ? this.game.league_person_result[0].id : null,
        opponent_id: this.game.opponent.id,
        opponent_result: this.game.opponent_result,
        opponent_result_id: this.game.league_person_result[1].id ? this.game.league_person_result[1].id : null,
        game_id: this.game.id,
        league_id: this.$route.params.id,
      },
    }
  },

我想要的是数据,如果不存在的话,它仍然可以工作,因为现在不提供数据时它的堆栈。

1 个答案:

答案 0 :(得分:0)

因此该错误表明this.game.league_person_result[0]undefined,这意味着您无法访问其id属性。仅在尝试抓住id之前检查该对象是否存在就足够了。

data() {
  const game = this.game
  const leagueId = this.$route.params.id
  const [league0, league1] = game.league_person_result

  return {
    edit: false,

    leagueGameResult: {
      person_id: game.person.id,
      person_result: game.person_result,
      opponent_id: game.opponent.id,
      opponent_result: game.opponent_result,
      game_id: game.id,
      league_id: leagueId
    },

    leagueGameResultEdit: {
      person_id: game.person.id,
      person_result: game.person_result,
      person_result_id: (league0 && league0.id) || null,
      opponent_id: game.opponent.id,
      opponent_result: game.opponent_result,
      opponent_result_id: (league1 && league1.id) || null,
      game_id: game.id,
      league_id: leagueId
    },
  }
},

我已经尝试了减少重复,但是在leagueGameResultleagueGameResultEdit几乎相同的情况下,还有很多事情可以做。

我还建议尝试将league_id移到道具上,而不要通过this.$route抓住它。 Vue Router允许您将路线参数作为道具。