LoginSignup
17
15

More than 5 years have passed since last update.

Nuxt.js 2でYoutubeプレイヤー埋め込み

Posted at

調べると

kaorun343/vue-youtube-embedがNuxt2のuniversalモードで動かなかった

の二つが出てきました。 kaorun343/vue-youtube-embedの方がよく使われてそうなのですが、Nuxt.jsのspaモードだと動作してuniversalモードだとエラーが発生して動かなかったです。

  • Unexpected token export
  • render function or template not defined in component: anonymous

などのエラーです。

Using vue-youtube-embed in Nuxt.js にある方法やrender function or template not defined in component: anonymousImport vue plugin correctly (unexpected token import) などをみつつ試したけどエラー回避できず

nteriovieira/vue-youtubeで動作した

エラー調査が疲れたので別の方が作ってるこちらで試したらうまく動いたのでこちらを使っていきます。

readmeに書いてる内容でそのまま動作します。

https://github.com/anteriovieira/vue-youtube

インストール

npm install vue-youtube
  • pages/index.vueをまるっと
index.vue
<template>
  <section class="container">
    <div>
      <h1 class="title">
        youtubeのテスト
      </h1>
      <youtube
        ref="youtube" 
        :video-id="videoId"
        :player-vars="{autoplay:1}"
        @playing="playing"
        @paused="paused"
        @ended="ended"
      />
    </div>
  </section>
</template>

<script>
import Vue from 'vue'
import VueYoutube from 'vue-youtube'

Vue.use(VueYoutube)

export default {
  components: { 
  },
   data () {
    return {
      videoId: 'oy-HyrxsPJE',
    }
  },

  methods: {
    playVideo() {
      this.player.playVideo()
    },
    //再生スタートした際に発火
    playing() {
      console.log('\o/ we are watching!!!')
    },
    //一時停止した際に発火
    paused() {
      console.log('paused')
    },
    //再生終了した際に発火
    ended() {
      console.log('ended')
    }
  }
}
</script>

<style>

.container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}

.title {
  font-family: 'Quicksand', 'Source Sans Pro', -apple-system, BlinkMacSystemFont,
    'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  display: block;
  font-weight: 300;
  font-size: 100px;
  color: #35495e;
  letter-spacing: 1px;
}

.subtitle {
  font-weight: 300;
  font-size: 42px;
  color: #526488;
  word-spacing: 5px;
  padding-bottom: 15px;
}

.links {
  padding-top: 15px;
}
</style>

こんな感じで動きます 再生、一時停止、停止などのイベントも取れてやりたいことできたのでこっちが良さそう。

17
15
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
17
15