[Vuejs]-How to make a video change when the source changes, when a new video is uploaded

0👍

Maybe make Video component that accepts url prop and use :key to make it rerender:

<template>
  <div id="app">
    <Video :url="videoUrl" :key="currentVideoId" />
    <div>
      <button v-for="v in videos" :key="v.id" @click="setVideoUrl(v.id)">
        {{ v.id }}
      </button>
    </div>
  </div>
</template>

<script>
import Video from "./components/Video";

export default {
  name: "App",
  components: {
    Video,
  },
  data() {
    return {
      videos: [
        {
          id: 1,
          url:
            "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4",
        },
        {
          id: 2,
          url:
            "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4",
        },
        {
          id: 3,
          url:
            "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4",
        },
      ],
      currentVideoId: 1,
    };
  },
  computed: {
    videoUrl() {
      const video = this.videos.find((vid) => vid.id === this.currentVideoId);
      return video.url;
    },
  },
  methods: {
    setVideoUrl(id) {
      this.currentVideoId = id;
    },
  },
};
</script>

<style>
</style>

Video component:

<template>
  <video
    autoplay="autoplay"
    muted
    loop
    controls
    class="theme-tournament-video-ultra"
    :style="{ width: '860px', height: '239px', 'background-color': 'grey' }"
  >
    <source :src="url" />
  </video>
</template>

<script>
export default {
  name: "Video",
  props: {
    url: String,
  },
};
</script>
<style scoped>
</style>

Codesandbox sample

Leave a comment