等待定义,然后调用函数-Vue.js

时间:2020-05-21 20:58:38

标签: javascript vue.js

在子组件中创建方法时,我很难确定特定功能。

我有此父路线/组件(League.vue):

在这个League.vue中,我渲染了一个子组件:

     <router-view :league="league" />

子组件:

<template>
  <div v-if="teams_present">
    <div class="page-container__table">
      <h3 class="page-container__table__header">Teams</h3>
    </div>
  </div>
</template>

<script>
export default {
  name: 'LeagueTeams',
  props: [
    'league'
  ],
  data () {
  },
  computed: {
    teams_present: function () {
      return this.league.teams.length > 0
    }
  }
}
</script>

错误:

 "TypeError: Cannot read property 'length' of undefined"

看来,computed回调是在可以设置prop之前调用的,我认为呢?如果将其更改为methods,它将永远不会被调用。该如何处理?

1 个答案:

答案 0 :(得分:1)

按照阿里的建议,您可以返回this.league.teams && this.league.teams.length > 0,这肯定可以。

但是,根据我的经验,为避免出现这种情况,并为了良好作法,请始终声明道具的类型。所以在你的道具中:

export default {
  name: 'LeagueTeams',
  props: {
    league: {
      type: Object,  // type validation Object
      default() { return {teams: [] }}  // add a default empty state for team, you can add more
    }
  },
  data () {
  },
  computed: {
    teams_present: function () {
      return this.league.teams.length > 0 // now the old code should work
    }
  }
}
</script>

这样做,您不必每次都检查this.league.teams的边缘情况,因为您可能需要使用方法或< strong> <template> html

更新:另一个建议是,如果您使用的是 vue-cli 4 ,则可以使用可选链接和无效合并。

return this.league?.teams.length ?? false // replace with only this line will work

希望这将为您提供2种在这种情况下应对的方式,具体取决于您可以选择哪种方式