[Vuejs]-How to access data in custom component?

0👍

Map your club data as object so you don’t have to perform find operation for each player, It will give you club in O(1) time rather than O(n) e.g make a computed prop mappedClubs and pass it in player cards

mappedClubs(){
  return this.clubs.reduce((r,c) =>{
   r[c.id] = r
   return r
  },{})
}

and in your card component just access club information something like that

<div> club name : {{ mappedClubs[player.club_id].name}} </div>

0👍

One thing you can do in order to avoid a second iteration is to use a Map for the clubs.

data () {
 return {
  players: [/* ... */],
  clubs: new Map([
   [1, { name: "Liverpool", logo: "Liverpool.png" }],
   [2, { name: "Ajax Amsterdam", logo: "ajax_amsterdam.png" }]
  ])
 }
}

So that you can use this method in order to get the club information depending on the provided clubId.

methods: {
  getClubById (clubId) {
   return this.clubs.get(clubId)
 }
}

Putting it all together:

<Card 
 v-for="player in players"
 :key="player.id"
 :playerClub="getClubById(player.club_id)"
/>

I personally like this approach more as you have to iterate over the players array only once, and getting a specific club requires O(1) time complexity.(Here is more about this)

Leave a comment