简体   繁体   中英

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

In this league.vue I render a child component:

     <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? and if a change it to methods it never gets called. How do I handle this case?

As Ali suggested, you can return this.league.teams && this.league.teams.length > 0 , which definitely will work.

However, as my experience, to avoid these situation, and for good practice, always declare the type of the 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

Update: Another suggestion is if you are using vue-cli 4, you can use Optional chaining and nullish coalescing.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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