En mi vue -app, trato de recorrer algunos elementos de video, obtener su ID de YouTube y buscar sus miniaturas.
así que tengo:
<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>luego tengo
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() } Por alguna razón que desconozco, esto me da el error TypeError: Cannot read properties of undefined (reading 'thumbnails')
¿Alguien puede decirme qué estoy haciendo mal? ¿Y cómo puedo aplicar esas imágenes al final?
Primero, debe usar una función de flecha como devolución de llamada para el método forEach para obtener acceso a la instancia del componente, segundo, debe colocar this.thumbnails.push(video_thumbnail); dentro del bloque de condiciones:
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); } });