简体   繁体   English

等待定义后再调用 function - Vue.js

[英]Wait for definition before calling function - Vue.js

When it comes to creating methods in child components I'm having a hard time figuring a particular feature out.当谈到在子组件中创建方法时,我很难弄清楚一个特定的特性。

I have this parent route/component (League.vue):我有这个父路由/组件(League.vue):

In this league.vue I render a child component:在这个 League.vue 中,我渲染了一个子组件:

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

Child component:子组件:

<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>

ERROR:错误:

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

So it appears that the computed callback is called before the prop can be set, I think?所以看起来computed的回调是在可以设置道具之前调用的,我想? and if a change it to methods it never gets called.如果将其更改为methods ,它将永远不会被调用。 How do I handle this case?我该如何处理这种情况?

As Ali suggested, you can return this.league.teams && this.league.teams.length > 0 , which definitely will work.正如阿里建议的那样,您可以返回this.league.teams && this.league.teams.length > 0 ,这肯定会起作用。

However, as my experience, to avoid these situation, and for good practice, always declare the type of the Props.但是,根据我的经验,为了避免这些情况,并且为了良好的实践,总是声明 Props 的类型。 So in your props:所以在你的道具中:

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>

By doing this, you don't need to care much about checking the edge case of this.league.teams every time, since you may need to call it again in methods or in the <template> html通过这样做,您不必每次都检查this.league.teams的边缘情况,因为您可能需要在方法<template> html中再次调用它

Update: Another suggestion is if you are using vue-cli 4, you can use Optional chaining and nullish coalescing.更新:另一个建议是,如果您使用vue-cli 4,您可以使用可选链接和无效合并。

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

Hope this will help you 2 more ways to deal with in these situations, and depends on situations you can choose the most suitable one希望这将帮助您在这些情况下的另外两种处理方法,并且取决于您可以选择最合适的一种

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM