赞
踩
要实现在 Vue 2 中的组件里,同一时间只能播放一个 <video>
标签,你可以使用 Vue 的事件监听和组件之间的通信。以下是一个简单的示例:
currentPlayingVideo
),用于存储当前播放的 <video>
组件的引用。VideoPlayer
)。<video>
标签的 play
事件,并使用一个自定义事件(如 video-play
)向父组件发送当前播放的 <video>
组件的引用。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>
子组件(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>
在这个示例中,当一个 <video>
组件开始播放时,它会暂停其他正在播放的 <video>
组件,确保同一时间只有一个 <video>
标签在播放。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。