简体   繁体   中英

How to pause all other videos while playing a single video in Vue.js/Nuxt.js?

I have a feed component developing on a nuxt.js appilcation where activity(post a video,like,comment) of multiple users will be shown. We can assume like facebook's newsfeed, we have an array of videos. An user can click and play any of them.

feed.vue

<div v-for="(item, vidIndex) in videos":key="vidIndex">
    <div>
        <video :src="item.url" type="video/mp4"></video>
    </div>
</div>

Problem is, user can click multiple videos to play and all the videos are being played and creates a mess. Now all I want is, if any user click on a video to play, all the other videos had played before should be paused. Is there any idea how can I do this?

Here's a working solution (once you update the video URLs):

<template>
  <div>
    <div v-for="video in videos" :key="video.ref">
      <video :ref="video.ref" :src="video.url" type="video/mp4" @click="onClick(video)"></video>
    </div>
  </div>
</template>

<script>
export default {
  computed: {
    videos() {
      return [
        { url: 'https://path/to/your/video.mp4', ref: 'video0' },
        { url: 'https://path/to/your/video.mp4', ref: 'video1' },
        { url: 'https://path/to/your/video.mp4', ref: 'video2' },
      ];
    },
  },
  methods: {
    onClick({ ref }) {
      // Loop over all videos
      this.videos.forEach((video) => {
        // Get the DOM element for this video
        const $video = this.$refs[video.ref][0];
        // Play the video that the user clicked
        if (video.ref === ref) $video.play();
        // Pause all other videos
        else $video.pause();
      });
    },
  },
};
</script>

Note that here I'm defining videos as a computed property. It may be a prop in your case. This example assigns a ref string to each video so the video can later be directly manipulated in the onClick handler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM