How do I programmatically bind in video player URLs in Nuxt/Vue?

1.2k Views Asked by At

I was looking for an idea of how to programmatically bind in video player urls. I understand the idea of using img and doing v-for and a :src, but the url for my videos get put in the data of the script. Is it possible to bind and make these programmatic as well? Here is an example of a working script now, but I just have to replace this as a component for every single video manually.

<template>
  <div class="player">
    <client-only>
      <video-player
        ref="videoPlayer"
        :options="playerOptions"
      />
    </client-only>
  </div>
</template>

<script>
export default {
  name: "index",
  data() {
    return {
      playerOptions: {
        sources: [{
            type: 'application/x-mpegurl',
            src: 'myvideo.m3u8'
        }],

The above code is working, but I need to have a component for every single video. Then in each component put the same code, but change the name of the src for the m3u8 video. Ideally, I would want to just pass something from an api into the src of the m3u8 and create one dynamic component. The question is, how would I make this dynamic component?

I tried something like this, but couldnt do a :src in the script.

<template>
  <div class="player">
    <client-only>
      <video-player
        ref="videoPlayer"
        :options="playerOptions"
      />
    </client-only>
  </div>
</template>

<script>
export default {
  name: "index",
  data() {
    return {
      playerOptions: {
        sources: [{
            type: 'application/x-mpegurl',
            :src: video.url
        }], 
1

There are 1 best solutions below

0
On

@tomdale I'm not sure if i'm understanding your question correctly, but if you want something dynamic you're probably best to remove playerOptions from your data() property and turn it into a computed property.

It could then look something like this,

computed: {
    playerOptions() {
      return {
        sources: [{
          type: 'application/x-mpegurl',
          src: this.video.url
        }]
      }
    },
}

Your question doesn't really show where you're getting the video and video.url data from, but if the component is working with a collection of video data, you could do something like,

    playerOptions() {
      let sources = []
      let i = 0
      while (i < this.videos.length) {
        sources.push({
          type: 'application/x-mpegurl',
          src: this.videos[i].url
        })

        i++
      }

      return sources
    },

You'll be be able to reference playerOptions the same way that you were in when it was in data(), ie this.playerOptions, however now it will be dynamic.