LoginSignup
25
25

More than 5 years have passed since last update.

NuxtでYouTubeプレイヤーを埋め込む

Last updated at Posted at 2018-12-30

VueでYouTubeプレイヤーを埋め込むのに anteriovieira/vue-youtube というライブラリがあるのでNuxtではこれを読み込んで使えばOK。

YouTubeがiframe 組み込みの YouTube Player APIを提供していて、それを実装した gajus/youtube-player というのがあり、それを anteriovieira/vue-youtube が組み込んでいる形。
ちょっと、ややこしいですね。

実装

動作を確認できるデモページを用意しました。
https://nuxt-playground.netlify.com/plugins-sample/vue-youtube/

ポイントとしては、
playVideo や pauseVideo なんかのコントロールは iframe APIの再生制御がそのまま使える。
play や pause なんかのiframe APIのイベントはemitで発火するようです。

pages/plugins-sample/vue-youtube.vue
<template>
  <div>
    <h1><a href="https://github.com/anteriovieira/vue-youtube">vue-youtube</a></h1>
    <youtube
      ref="youtube"
      :video-id="videoId"
      @ready="ready"
      @ended="ended"
      @playing="playing"/>
    <button @click="playVideo">play</button>
    <button @click="pauseVideo">pause</button>
    <button @click="stopVideo">stop</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      videoId: 'nteDXuqBfn0'
    }
  },
  computed: {
    player() {
      return this.$refs.youtube.player
    }
  },
  methods: {
    playVideo() {
      this.player.playVideo()
    },
    pauseVideo() {
      this.player.pauseVideo()
    },
    stopVideo() {
      this.player.stopVideo()
    },
    ready() {
      console.log('ready')
    },
    ended() {
      console.log('ended')
    },
    playing() {
      console.log('playing')
    }
  }
}
</script>
plugins/vue-youtube.js
import Vue from 'vue'
import VueYoutube from 'vue-youtube'

Vue.use(VueYoutube)
25
25
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
25