[英]Wait for definition before calling function - 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
的回調是在可以設置道具之前調用的,我想? 如果將其更改為methods
,它將永遠不會被調用。 我該如何處理這種情況?
正如阿里建議的那樣,您可以返回this.league.teams && this.league.teams.length > 0
,這肯定會起作用。
但是,根據我的經驗,為了避免這些情況,並且為了良好的實踐,總是聲明 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>
通過這樣做,您不必每次都檢查this.league.teams
的邊緣情況,因為您可能需要在方法或<template>
html中再次調用它
更新:另一個建議是,如果您使用vue-cli 4,您可以使用可選鏈接和無效合並。
return this.league?.teams.length ?? false // replace with only this line will work
希望這將幫助您在這些情況下的另外兩種處理方法,並且取決於您可以選擇最合適的一種
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.