Javascript 在调用函数-Vue.js之前等待定义

Javascript 在调用函数-Vue.js之前等待定义,javascript,vue.js,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-contain

当涉及到在子组件中创建方法时,我很难弄清楚一个特定的特性

我有这个父路由/组件(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>

我想,似乎在设置道具之前调用了
computed
回调?如果将其更改为
methods
,则永远不会调用它。如何处理此案例?

正如阿里所建议的,您可以返回
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&&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>
return this.league?.teams.length ?? false // replace with only this line will work