Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

vue.js - Run multiple YouTube video dynamically using YouTube API

Case

I am implementing youtube video in VUE JS using youtube API, Video is playing in the modal, when the user clicks on the next and previous button then new youtube video will be played in modal

Problem

I want to reinitialize the youtube player with a new ID dynamically and destroy the old youtube instance

Code

  data () {
    player: ''
  },

  onYouTubeIframeAPIReady (youtubeVideoId) {
  const _ = this
  this.player = new window.YT.Player('player', {
    playerVars: { autoplay: 1, controls: 1 },
    videoId: youtubeVideoId,   <<<<<<<------------------------ everytime new id passed then 
    youtube player must reinitialize
    
    events: {
      onReady: _.onPlayerReady,
      onStateChange: _.onPlayerStateChange
    }
  })
},
onPlayerReady (evt) {
  console.log('Player ready')
  evt.target.playVideo()
},
onPlayerStateChange (evt) {
  // this.player.loadVideoById(youtubeVideoId)
  // this.player.stopVideo()
  // evt.target.destroy()
  console.log('Player state changed', evt)
},
loadNext () {
     //some id will be passed
     this.onYouTubeIframeAPIReady(nextId)
},
loadPreviouse () {
     //some id will be passed
    this.onYouTubeIframeAPIReady(previousId)
}

enter image description here

You can see in the image loadnext and loadprevious pass new ID to this function onYouTubeIframeAPIReady to play the new video

I could not found any dynamic solution. Another possible solution is to embed the new youtube iframe code again and again which works fine. But in this solution youtube video not autoplay with sound


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...