当前位置:   article > 正文

vue2,组件里有多个video, 但是我想同一时间只能有一个播放,怎么办

vue2,组件里有多个video, 但是我想同一时间只能有一个播放,怎么办

要实现在 Vue 2 中的组件里,同一时间只能播放一个 <video> 标签,你可以使用 Vue 的事件监听和组件之间的通信。以下是一个简单的示例:

  1. 在父组件中创建一个数据属性(如 currentPlayingVideo),用于存储当前播放的 <video> 组件的引用。
  2. 将父组件的数据属性传递给子组件(如 VideoPlayer)。
  3. 在子组件中,监听 <video> 标签的 play 事件,并使用一个自定义事件(如 video-play)向父组件发送当前播放的 <video> 组件的引用。
  4. 在父组件中,监听 video-play 自定义事件,并更新 currentPlayingVideo 数据属性。同时,暂停其他正在播放的 <video> 组件。

以下是一个简化的代码示例:

父组件:

<template>
  <div>
    <video-player
      v-for="(video, index) in videos"
      :key="index"
      :video="video"
      :current-playing-video="currentPlayingVideo"
      @video-play="onVideoPlay"
    ></video-player>
  </div>
</template>

<script>
import VideoPlayer from './VideoPlayer.vue';

export default {
  components: {
    VideoPlayer
  },
  data() {
    return {
      videos: [...], // 视频列表
      currentPlayingVideo: null // 当前播放的视频
    };
  },
  methods: {
    onVideoPlay(playingVideo) {
      if (this.currentPlayingVideo && this.currentPlayingVideo !== playingVideo) {
        this.currentPlayingVideo.pause();
      }
      this.currentPlayingVideo = playingVideo;
    }
  }
};
</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

子组件(VideoPlayer.vue):

<template>
  <div>
    <video
      ref="videoRef"
      :src="video.src"
      @play="onPlay"
    ></video>
  </div>
</template>

<script>
export default {
  props: {
    video: Object,
    currentPlayingVideo: Object
  },
  methods: {
    onPlay() {
      this.$emit('video-play', this.$refs.videoRef);
    },
    pause() {
      this.$refs.videoRef.pause();
    }
  }
};
</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

在这个示例中,当一个 <video> 组件开始播放时,它会暂停其他正在播放的 <video> 组件,确保同一时间只有一个 <video> 标签在播放。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/468783
推荐阅读
相关标签
  

闽ICP备14008679号