首页 > 解决方案 > data() 中的错误:“TypeError:this.game.league_person_result[0] 未定义”

问题描述

如果在 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,
      },
    }
  },

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

标签: vuejs2

解决方案


所以错误提示this.game.league_person_result[0]is 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
    },
  }
},

我试着减少一点重复,但还有很多可以做的leagueGameResult,而且leagueGameResultEdit几乎是一样的。

我还建议尝试将它移到league_id一个道具上,而不是通过this.$route. Vue Router 允许你将路由参数作为 props 注入。


推荐阅读