Robert Dempsey
Robert Dempsey

Reputation: 67

How do I bind this src to an iFrame in vue js?

How should I bind to an iframe src with something received back via the YouTube data api?

Can I set a string inside :src and concatenate onto the end of it?

/embed/'this.param.videoId'

The response returns an Id {{ video.snippet.resourceId.videoId }}, but the url contains other parts src=“https://www.youtube.com/embed/xxx

Any help greatly appreciated!

Thanks

Upvotes: 2

Views: 9793

Answers (3)

atazmin
atazmin

Reputation: 5667

Here is what is working for me with Bootstrap V5 css

<template>
  <section class="video-player-container">
    <div class="video-player-row">
      <div
        class="video-player ratio"
        :class="`ratio-${group.videoAspectRatio}`"
      >
        <iframe
          loading="lazy"
          :src="`https://www.youtube.com/embed/${getIdFromURL(group.videoEmbedLink)}?rel=0`"
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
          allowfullscreen
        />
      </div>
    </div>
  </section>
</template>

<script>
export default {
  name: 'VideoPlayer',
  props: {
    group: {
      type: Object,
      required: true
    }
  },
  methods: {
    getIdFromURL (url) {
      const youtubeRegexp = /https?:\/\/(?:[0-9A-Z-]+\.)?(?:youtu\.be\/|youtube(?:-nocookie)?\.com\S*[^\w\s-])([\w-]{11})(?=[^\w-]|$)(?![?=&+%\w.-]*(?:['"][^<>]*>|<\/a>))[?=&+%\w.-]*/ig
      let id = url.replace(youtubeRegexp, '$1')

      if (id.includes(';')) {
        const pieces = id.split(';')

        if (pieces[1].includes('%')) {
          const uriComponent = decodeURIComponent(pieces[1])
          id = `http://youtube.com${uriComponent}`.replace(youtubeRegexp, '$1')
        } else {
          id = pieces[0]
        }
      } else if (id.includes('#')) {
        id = id.split('#')[0]
      }

      return id
    }
  }
}
</script>

<style scoped lang="scss">
  .video-player {
    &-container {
      @include make-container();
      @include default-max-widths();
    }

    &-row {
      @include make-row();
    }
  }
</style>

Upvotes: 1

Robert Dempsey
Robert Dempsey

Reputation: 67

This worked:

 :src="ytEmbedUrl + video.snippet.resourceId.videoId"

Upvotes: 2

Ohgodwhy
Ohgodwhy

Reputation: 50767

iframe resolving only when there's a videoId:

<iframe v-if="videoId" :src="mySrc"></iframe>

computed property:

computed: {
  mySrc: {
    get: function() {
      //concat using template literal
      return `https://www.youtube.com/embed/${this.videoId}`
    }
  }
}

data property:

{
  videoId: false
}

Your method to assign to it:

methods: {
  getMyVideo() {
    video = // get my video code
    this.videoId = video.snippet.resourceId.videoId
  }
}

Or just inline it if you're super lazy:

<iframe src="`https://www.youtube.com/embed/${videoId}`"></iframe>

Upvotes: 1

Related Questions