0

In my vue-app I try to loop through some video-items, get their youtube-id and fetch their thumbnails.

so I have:

<div class="videos">
  <div v-for="(video, index) in videos" :key="index" :youtube-id="video.id" class="video-item">
    <div @click="play(video.id)">
     <img :src="thumbnail" :width="420" :height="240" />
    </div>
  </div>
</div>

then I have

data(){
  return {
    thumbnail : '',
    thumbnails: [] // don't know if I can use that
   }
},

methods: {
   getVideoThumbNails(){
      const videos = document.querySelector(".videos");
      const iframes = videos.querySelectorAll(".video-item");

      iframes.forEach(function (item, index) {
        let youtube_video_id = item.getAttribute("youtube-id");

        if (youtube_video_id.length === 11) {
           const video_thumbnail = "http://img.youtube.com/vi/" + youtube_video_id + "/maxresdefault.jpg";
        }
        
        // this.thumbnail = video_thumbail
        this.thumbnails.push(video_thumbnail);
     });
   }
},
mounted(){
 this.getVideoThumbNails() 
}

For some reason I don't know, this gives me the error TypeError: Cannot read properties of undefined (reading 'thumbnails')

Can someone tell me what I'm doing wrong? And how can I apply those images in the end?

ST80
  • 3,565
  • 16
  • 64
  • 124

1 Answers1

1

First you should use an arrow function as callback for the forEach method in order to get access to the component instance, second you must put the this.thumbnails.push(video_thumbnail); inside the condition block :

      iframes.forEach( (item, index) =>{
        let youtube_video_id = item.getAttribute("youtube-id");

        if (youtube_video_id.length === 11) {
           const video_thumbnail = "http://img.youtube.com/vi/" + youtube_video_id + "/maxresdefault.jpg";

     // this.thumbnail = video_thumbail
        this.thumbnails.push(video_thumbnail);
        }
        
       
     });
Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164